Top 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.

You may find that iterating over a sparse array to apply a certain transformation is hard.

To solve this, you can use Array.apply when creating the array.

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.

A workaround that people usually resort to is to pass either null or undefined.

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. We’ll use this to our advantage.

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.

Let me know in comment if you have any other ideas or hacks.

Arif Khoja
Arif Khoja is a Developer. He is a Javascript Enthusiatic who loves logical programming and has first hand experience in building a cutting edge internet product using Angular. He is also an open source freak and keen about learning and sharing. He writes Javascript both frontend and backend. He loves learning and sharing tech all the time. He also has a hands on experience in SEO and writes articles about latest emerging technologies.
Arif Khoja on FacebookArif Khoja on GoogleArif Khoja on InstagramArif Khoja on LinkedinArif Khoja on Twitter

Leave a Reply

%d bloggers like this: