Three JavaScript Array Hacks
Arrays are everywhere in JavaScript and with the new spread operatorsintroduced in ECMAScript 6, you can do awesome things with them.
In this post I will show you three useful tricks you can use when programming:
1. Iterating through an empty array
JavaScript arrays are sparse in nature in that there are a lot of holes in them. Try creating an array using the Array’s constructor and you will see what I mean.
> const arr = new Array(4); [undefined, undefined, undefined, undefined]
You may find that iterating over a sparse array to apply a certain transformation is hard.
> const arr = new Array(4); > arr.map((elem, index) => index); [undefined, undefined, undefined, undefined]
To solve this, you can use
Array.apply
when creating the array.> const arr = Array.apply(null, new Array(4)); > arr.map((elem, index) => index); [0, 1, 2, 3]
A nicer way to iterate through an empty array is to use spread operators. Shout-out to Hugo Caillard for pointing that out.
> const arr = [...new Array(4)]; > arr.map((elem, index) => index); [0, 1, 2, 3]
2. Passing an empty parameter to a method
If you want to call a method and ignore one of its parameters, then JavaScript will complain if you keep it empty.
> method('parameter1', , 'parameter3'); Uncaught SyntaxError: Unexpected token ,
A workaround that people usually resort to is passing either
null
or undefined
.> method('parameter1', null, 'parameter3') // or > method('parameter1', undefined, 'parameter3');
I personally don’t like using
null
since JavaScript treats it as an object
and that’s just weird. With the introduction of spread operators in ES6, there is a neater way of passing empty parameters to a method. As previously mentioned, arrays are sparse in nature and so passing empty values to it is totally okay.> method(...['parameter1', /* parameter2 */, 'parameter3']);
3. Unique array values
I always wonder why the Array constructor doesn’t have a designated method to facilitate the use of unique array values. Spread operators are here for the rescue. Use spread operators with the
Set
constructor to generate unique array values.> const arr = [...new Set([1, 2, 3, 3])] [1, 2, 3]

There you have it: Three JavaScript hacks that every developer should keep in their toolbox.
Comments
Post a Comment