The wonder of Javascript’s array

Array is one of the most important and elegant features in Javascript. Developers, especially those coming from statically typed languages like Java or C# tend to overlook the built-in methods of Javascript’s array.

Photo by Junsheng Chen on Unsplash

There are two main ways to create an array in Javascript.

Using Array class:

and using [] syntax:

Javascript is a dynamically typed language, so each item in the array can be of a different type. Think of it as an ArrayList in Java, or List<object> in C#.

Four ways to loop through an array

There are more ways to traverse an array than the four methods listed here, but they are the ones I find most useful.

Traditional for loop:

If you don’t need the index and just want to have access to the value of each item, for of syntax is more concise:

If functional programming is your jam, map and forEach are higher order functions that were introduced with ES6.

Similar to map, forEach traverses each item in the array. However, it does not return any value. Any return value inside the arrow function will just be ignored.

Using array as queue

A queue is defined as

In computer science, a queue is a collection of entities that are maintained in a sequence and can be modified by the addition of entities at one end of the sequence and the removal of entities from the other end of the sequence.

In short, a queue allows data to be accessed in a First-In-First-Out (FIFO)manner. Many programming languages have a dedicated data structure for a queue. An array would suffice in Javascript, with push method to enqueue an item and shift method to dequeue an item.

Using array as stack

Stack is a data structure that supports First-In-Last-Out access principle. It is defined as:

In computer science, a stack is an abstract data type that serves as a collection of elements, with two main principal operations: Push, which adds an element to the collection, and. Pop, which removes the most recently added element that was not yet removed.

Javascript’s Array does have push and pop methods that do exactly what it says on the tin.

Inserting items

As we have seen from the examples above, push method adds an item at the end of the array. If you want to append another array to the end of the current array, concat is what you need.

What’s about inserting an item at the other end?

unshift method can be used to add an item at the beginning of the array. unshift returns the length of the array after the item has been inserted.

Inserting an item in the middle of an array is also possible using splice method:

Removing items

splice(index, howMany) will do the job.

Conclusion

This article only scratches the surface of the wonder of Javascript’s array. Make sure you checkout the documentation for more in-depth information. What is your favourite feature of Javascript’s array?

Software developer