1. Iterating through an empty array
> 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]
2. Passing an empty parameter to a method
> method('parameter1', , 'parameter3'); Uncaught SyntaxError: Unexpected token ,
A workaround that people usually resort to is to pass either
> method('parameter1', null, 'parameter3') // or > method('parameter1', undefined, 'parameter3');
I personally don’t like using
> method(...['parameter1', , 'parameter3']); // works!
3. Unique array values
I always wonder why the Array constructor does not have a designated method to facilitate the use of unique array values. Spread operators are here for the rescue. Use spread operators with the
Setconstructor to generate unique array values.
> const arr = [...new Set([1, 2, 3, 3])]; [1, 2, 3]
Let me know in comment if you have any other ideas or hacks.