Arrays In JavaScript

This article examines the most popular data structure in JavaScript – arrays. We have already examined arrays in Java in a great detail. This post was written as one of the readers asked a comparison of the most popular data structure viz. array in two of the most popular programming languages viz. Java & JavaScript.

What are arrays?

Arrays are one of the most versatile and widely used data structures. An array is a simplest collection – meaning it encapsulates the functionality of a number of variables. For example, you can have the following array in JavaScript:

Though, it is not idiomatic JavaScript but the above array can be used to indicate details of a JavaScript coder such as name, age and income.

JavaScript arrays Vs. arrays in other languages

There are minimalist languages out there such as C which offer arrays as the only data structure. Other more sophisticated data structures can and are build using the power of arrays. There are a few other higher level programming languages such as Python which offer List and Dictionary as ready made data structures. (Technically, there are tuples also but their usage is rare). Arrays in their indexed and associative forms are also the mainstay of PHP. Each of these languages has a slightly different take on arrays.

There are a few points to remember about JavaScript arrays:

  1. They are dynamic. The size of the array grows to accommodate the elements. The programmer does not have to worry about overflows and segmentation faults.
  2. They are objects. They are aware of their size by virtue of the length property.
  3. They can contain elements of different data types and may even contain other arrays.
  4. There are two flavors of arrays – numeric indexed and associative. Numeric arrays start with index 0.
  5. They do not necessarily represent contiguous memory locations.
  6. It is possible (and quite common) to have arrays with holes. You can add undefined as well as null elements in an array –

The above code displays ,,1000

The , , as the second element adds undefined to the array.

Declaring and using JavaScript arrays

As with most things in JavaScript, there are two distinct ways of declaring arrays. One uses the Array object and the other uses literal notation. The code below shows both ways:

The literal notation is a syntactic sugar and the end result of both ways of declaration is the same. The only difference is that when you pass a single integer parameter to the Array constructor it is interpreted as the desired length of the new array and has all the elements as undefined. Consider the following two arrays

The argument “2” causes the string 2 to be part of the array, but the integer 2 is interpreted as the length of the new array.

Another interesting feature of JavaScript arrays is that trying to access an array element beyond the length of the array is not an error. Other languages such as Java or C generally treats this as no less than Adam’s sin, JavaScript remains silent about such access.  It simply resizes the array and ‘fills’ the unused space with undefined.

This feature leads to holes in arrays and therefore, special care must be taken during iteration. Always check for the element being null or undefined before invoking an operation on an element of the array.

Manipulating individual elements

Accessing is quite intuitive. It’s general format is array[index].

Similarly, modifying is also quite simple. It’s general format is array[index] = newValue.

Adding a new value to an array is syntactically same as modifying a value –

array[index] = newValue.

The catch while adding a new element is the issue of holes. These gaps in the array do not waste any memory but force you to do extra checks.

It’s possible to delete an element using the delete keyword. The delete operation causes the element to be replaced by undefined. Consider the session below –

 Iterating JavaScript Arrays

There are multiple distinct ways of visiting each element in order. Array iteration can be done using

  1. Traditional for loop
  2. for…in loop (usage both widespread and dangerous)
  3. The forEach loop
  4. for…of loop
  5. Using a combination of values() and next() methods – the traditional approach as described in the GOF Iterator pattern.
  6. while loop
  7. map function

Let’s start with the simplest and surest way of iterating arrays. The example below demonstrates for loop and for…in loop. (Iteration methods # 1 and 2 in above list)

Note that for…in loop selects the index not the value at the index. There are other languages such as PHP, Java and Python that have for…each mechanism. for…in is a different from for…each. A for…in can be used to iterate over any JavaScript object. It’s one of the oldest forms and hence more widely supported than the newer iteration methods. As indicated above for…in loop suffers from the problem of holes. The other great disadvantage of the for…in loop is that it does not guarantee the order of iteration. So, use this form if you want to process all the elements regardless of the position in which they appear during iteration.

The forEach method is demonstrated in the code below –

Remember that methods # 4 and 5 are available only in ECMAScript2015 onwards. So, they may or may not be there in your dev environment and in client’s browser.

The code below demonstrates the usage of for…of loop

The values() method when invoked on an array returns an iterator. There are other iterator factory methods that can be used –

  1. keys() – returns an iterator that gives the index of the elements
  2. entries() – returns an iterator that provides an array of [key, value]

The next() in while loop can be used to iterate over the iterator object.

In case the values() method does not work, you can try entries() as follows –

Similarly, it is quite straightforward to use the keys() iterator factory –

It’s quite straight forward to use the while loop –

A slightly functional way of iterating over the array is using the map function. The following code demonstrates a typical usage form of map method –

Conclusion/Quiz/Self Test

This post answered the following questions –

  1. What are arrays?
  2. How arrays in JavaScript differ from arrays in other programming languages?
  3. How to declare an array?
  4. How to manipulate individual elements of JavaScript array?
  5. How to iterate over JavaScript Arrays?

Related Posts

We will continue bringing up such posts examining differences between various languages as and when we receive request for same.

Leave a comment

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