Jagroop Singh

Posted on

# Top JavaScript Tips

As one know that our IT Industry is nothing without JavaScript. JavaScript plays a very important role in the development of Websites, Mobile App, Desktop Apps etc.

Also, it's not possible to master JavaScript or any other language. So today, I come up with the Tricks and Tips of JavaScript that help in my career for Software Development.

So let's go with Jungkook 🧡 ,

TOP TRICKS AND TIPS :

Flatten the array of the array : In this, we will learn about how to flatten a deeply nested array of arrays by using Infinity in flat.

``````var array = [1, 2, [3,4,5,[6,7,8[9,10]]]];
//flatten array of array
array.flat(Infinity)

//Output
// [1,2,3,4,5,6,7,8,9,10]
``````

Alphabetically Sorting: As we know that for sorting we have to write a long code and use different algorithms like Bubble, Insertion, Merge Sort etc. But one can sort an array of alphabets in just 2 lines of code.

``````let array = ["j", "u", "n", "g", "k", "o" ,"o" ,"k"];
console.log( array.sort((a, b) => a.localeCompare(b)));

// Output
['g', 'j', 'k', 'k', 'n', 'o', 'o', 'u']
``````

Performance Calculation : This tip I personally used to calculate the performance of JavaScript Program.

``````const {performance} = require('perf_hooks');
const starttime = performance.now();
let array = ["j", "u", "n", "g", "k", "o" ,"o" ,"k"];
console.log( array.sort((a, b) => a.localeCompare(b)));

const endtime = performance.now();
const totaltime = starttime - endtime
console.log("This takes "+totaltime +" milisecond");

//OUTPUT
[ 'g', 'j', 'k', 'k', 'n', 'o', 'o', 'u' ]
This takes -6.933455999940634 milisecond
``````

Use === instead of = : The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==.

``````[5] === 5   // is false
[6]  == 6    // is true
'1' == 1     // is true
'1' === 1    // is false
[]   == 0     // is true
[] ===  0     // is false
'' == false   // is true but true == "a" is false
'' === false // is false
``````

Sum all the values from an array : As we know that for getting Sum of array we have to use for loop. But with this shortcut, no more use of loop is need. It's just done with 2 lines of code.

``````var numbers =[1,2,3,4,5,6,7,8,9,10];
console.log(numbers.reduce((x,y) => x+y))

//Output
55
``````

That's all for this post, me with BTS meme's come with the next part of JavaScript Tips and Tricks soon.