5 JavaScript Tricks That Will Make Your Next Project Easier

Posted by TotalDC

Earlier we talked about JavaScript Methods And Shorthands and now I will give you 5 JavaScript tricks that you probably didn’t know about but you definitely need in your next project.

Flatten The JavaScript Array Of The Array

I’m sure that you must deal with arrays in arrays that are probably nested in another array. This trick will help you flatten a deeply nested array inside array by using Infinity in flat.

let array = [123, 500, [1, 2, [34, 56, 67, [123, 3456], 900]], 845, [30252]]
//flatten array inside array


[123, 500, 1, 2, 34, 56, 67, 123, 3456, 900, 845, 30252]

Easy Exchange Variables

I’m guessing that when you have to swap variables, you use third variable called let’s say temp. But did you know that you can use this trick and get rid of that third variable that you use just for this reason? You can exchange variables by using destructuring.

let a = 6;
let b = 7;
[a,b] = [b,a]


console.log(a,b) // 7 6

Sort Alphabetically

Sorting is a common problem in programming and this tip will save your valuable time by writing a long code to sort a string alphabetically.

function sortAbc(arr)
  return arr.sort((a, b) => a.localeCompare(b));
let array = ["d", "c", "b", "a"]
console.log(sortAbc(array)) // ["a", "b", "c", "d"]

Shorten The Console.log

I can bet that you are writing console.log() many times a day. This trick will show how to shorten your console.log and speed up your coding.

let c = console.log.bind(document)
c("hello world")

Remove Duplicates

I’m sure that you encounter an array with duplicate values and use a loop way to get rid of these duplicates. This tip will help you remove duplicates the easy way.

const removeDuplicate = array => [...new Set(array)];

I hope you find this article useful and fun to learn these tips.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: