8 Useful JavaScript Tips & Tricks
Tags: javascript, tutorial, beginners, webdev
Published: 2022-04-28 02:36:11

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.

```js
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.

```js
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

```js
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.

```js
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.

```js
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.

```js
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.

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

```js
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,
- [Follow me on Twitter](https://twitter.com/JustE3saR)
- [Take a look at my open-source projects](https://github.com/6km)