3 JavaScript Array Hacks

Arrays are everywhere in JavaScript and with the new spread operators introduced in ECMAScript 6, you can do awesome things with them. In this post I will show you 3 useful tricks you can use when programming.

Thank you for reading this post, don't forget to subscribe!

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]

Read Full Article

Leave a Reply

Your email address will not be published. Required fields are marked *