DEV Community

Cover image for 8 Useful JavaScript Tips & Tricks
Mohammed Taha
Mohammed Taha

Posted on • Originally published at 6km.hashnode.dev

8 Useful JavaScript Tips & Tricks

We all know that JavaScript is great but sometimes we face some difficulties that we have to find solutions for.

In this article, I will share with you some tricks that you may need someday.

Convert all array elements to string

In this example, we are using the built-in javascript method .map() to loop around the elements and convert them to strings.

function allToString(array) {
    return array.map(elm => {
        return Array.isArray(elm) ? allToString(elm) : elm.toString()
    })
}

allToString([1, 2, 3, [4]])
// ๐Ÿ‘‰ [ '1', '2', '3', [ '4' ] ]
Enter fullscreen mode Exit fullscreen mode

Create a range of numbers

The range() function returns a sequence of numbers, starting from a specified number, and stops at a specified number.

function range(from, to) {
    return Array((to - from) + 1).fill(0).map(() => from++)
}

range(1, 10)
// ๐Ÿ‘‡
// [
//   1, 2, 3, 4,  5,
//   6, 7, 8, 9, 10 
// ]
Enter fullscreen mode Exit fullscreen mode

Check if a property exists in the object

var obj = {
    a: 1,
    b: 2,
    c: 3
}

var aExists = !!obj['a'] // true
var rExists = !!obj['r'] // false
var uExists = !!obj['u'] // false
Enter fullscreen mode Exit fullscreen mode

Remove a property from an object

We use the keyword delete that deletes both the value of the property and the property itself.

var obj = {
    name: 'John',
    age: 23,
    country: 'UK'
}

// Usage
delete obj.country;

// ๐Ÿ‘‡
// {
//   name: 'John',
//   age: 23
// }
Enter fullscreen mode Exit fullscreen mode

Replace empty strings in object with null values

In this trick, we loop around the keys of our object and replace it with a null if it's an empty string.

var obj = {
    a: '๐Ÿ’Ž',
    b: 'โœจ',
    c: '',
    d: '๐Ÿ”ฎ'
}

function replaceEmpty(object) {
    if (!object || typeof object !== "object") return;

    let newValues = Object.values(object).map(v => v.trim() ? v : null);
    let objectKeys = Object.keys(object);

    for (let i = 0; i < objectKeys.length; i++) {
        object[objectKeys[i]] = newValues[i]
    }

    return object
}

// Usage
replaceEmpty(obj)

// ๐Ÿ‘‡
// {
//     a: '๐Ÿ’Ž',
//     b: 'โœจ',
//     c: null,
//     d: '๐Ÿ”ฎ'
// }
Enter fullscreen mode Exit fullscreen mode

Return the longest string from an array of strings

Sorting the array using the built-in method .sort() made it easy. I sorted the array descending according to the length of the strings, then I return the first element of the array.

var arr = ['Hashnode', 'is', 'cool']

function findLongest(array) {
    return arr.sort((a, b) => b.length - a.length)[0]
}

// Usage
findLongest(arr)

// ๐Ÿ‘‰ "Hashnode"
Enter fullscreen mode Exit fullscreen mode

Check if all array elements are equal

The method .every() checks every element of the array, and tells us if they are all equal to the first one.

var arr1 = [true, true, true]
var arr2 = [false, true, true]
var arr3 = [1, 2, 3]

var check = (array) => new Set(array).size <= 1

// Usage
check(arr1) // true
check(arr2) // false
check(arr3) // false
Enter fullscreen mode Exit fullscreen mode

Reverse a string

To implement this trick, follow these steps:

  1. Split the string into an array of letters using .split("")
    ["H", "a", "s", "h", "n", "o", "d", "e"]
Enter fullscreen mode Exit fullscreen mode
  1. Reverse the array using .reverse()
    ["e", "d", "o", "n", "h", "s", "a", "H"]
Enter fullscreen mode Exit fullscreen mode
  1. And now, turn the letters into a string again using .join("")
    "edonhsaH"
Enter fullscreen mode Exit fullscreen mode
const reverse = (string) => string.split("").reverse().join("")

// Usage
reverse("Hello, World!") // !dlroW ,olleH
reverse("Hashnode")      // edonhsaH
reverse("ABC")           // CBA
Enter fullscreen mode Exit fullscreen mode

If you enjoyed this article, share it with your friends and colleagues!

Keep in touch,

Top comments (0)