JavaScript Shorthand tricks
Today, I will discuss some shorthand techniques for regularly used syntax to ace an interview and save our time while writing code.
Sum all the values from an array :
My initial instinct was to use a loop, but that would have been wasteful.
var num = [3, 5, 7, 2];
var sum = num.reduce((x, y) => x + y);console.log(sum); // returns 17
Using length to resize an array :
You can either resize or empty an array.
var array = [11, 12, 13, 14, 15]; console.log(array.length); // 5 array.length = 3; console.log(array.length); // 3 console.log(array); // [11,12,13]array.length = 0; console.log(array.length); // 0console.log(array); // []
Swap values with array destructuring
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
let a = 1, b = 2[a, b] = [b, a]console.log(a) // -> 2console.log(b) // -> 1
Filter Unique Values
The Set object type was introduced in ES6, and along with …, the ‘spread’ operator, we can use it to create a new array with only the unique values.
const arr = [1, 1, 4, 4, 5, 5, 2]const uniqueArray = [...new Set(arr)];console.log(uniqueArray); // Result: [1, 2, 4, 5]
Before ES6, isolating unique values would involve a lot more code than that!
This trick works for arrays containing primitive types: undefined, null, boolean, string and number . (If you had an array containing objects, functions or additional arrays, you’d need a different approach!)
Append an array to another array
We can use the concat() method, but it will create a new array and then merge the 2 arrays, while the below approach will merge the 2 arrays without creating a 2nd array.
var arr1 = [12 , "foo" , {name "Joe"} , -2458];var arr2 = ["Doe" , 555 , 100];Array.prototype.push.apply(arr1, arr2)/* arr1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
Thanks for your time and Hope you ace every interview !!