8 Useful JavaScript Tips & Tricks

8 Useful JavaScript Tips & Tricks

ยท

3 min read

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' ] ]

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 
// ]

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

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
// }

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: '๐Ÿ”ฎ'
// }

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"

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

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"]
    
  2. Reverse the array using .reverse()
    ["e", "d", "o", "n", "h", "s", "a", "H"]
    
  3. And now, turn the letters into a string again using .join("")
    "edonhsaH"
    
const reverse = (string) => string.split("").reverse().join("")

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

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

Keep in touch,

ย