Home > Hot in web development > 3 JavaScript Array Hacks

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.

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

admin
The WebRecital is a dedicated User Interface/User Experience professionals who come together to provide design and research workshops, portfolio reviews, and educational outreach to the greater Seattle area.
http://webrecital.com/

Leave a Reply

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