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:
1 | var jsCoder = ["Jane Doe", 25, "100,000"]; |
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:
- 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.
- They are objects. They are aware of their size by virtue of the length property.
- They can contain elements of different data types and may even contain other arrays.
- There are two flavors of arrays – numeric indexed and associative. Numeric arrays start with index 0.
- They do not necessarily represent contiguous memory locations.
- It is possible (and quite common) to have arrays with holes. You can add undefined as well as null elements in an array –
1 2 | var arr = [null, , 1000] arr |
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:
1 2 | var num1 = new Array(1, 2); var num2 = [1, 2] |
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
1 2 3 4 | var arr1 = new Array(2) var arr2 = new Array("2") // you can skip both the length and elements var arr3 = new Array(); |
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.
1 2 3 | var arr2 = new Array( "2") arr2[0] // refers to the element at location 0 with value "2" arr2[20] // 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 –
1 2 3 4 5 6 7 8 9 | arr2[1] arr2[1] = "CodingRaptor.com"; CodingRaptor.com arr2 2,CodingRaptor.com delete arr2[0] true arr2 ,CodingRaptor.com |
Iterating JavaScript Arrays
There are multiple distinct ways of visiting each element in order. Array iteration can be done using
- Traditional for loop
- for…in loop (usage both widespread and dangerous)
- The forEach loop
- for…of loop
- Using a combination of values() and next() methods – the traditional approach as described in the GOF Iterator pattern.
- while loop
- 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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var iterArray = ["Coding", "Raptor"]; for(var position = 0; position < iterArray.length; position++) { print(iterArray[position]); // replace with alert or document.writeln if desired } Coding Raptor for(var index in iterArray){ // for...in selects the index of enumerable print(iterArray[index]); } Coding Raptor |
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 –
1 2 3 4 5 6 7 8 9 10 11 12 | var website = ["Coding", "Raptor"]; website.forEach(function(element) { console.log(element); }); //output /* Coding Raptor */ |
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
1 2 3 4 5 6 7 8 9 | var a = [1, 2, 3] Array [ 1, 2, 3 ] for(aValue of a) { console.log(aValue); } 1 2 3 |
The values() method when invoked on an array returns an iterator. There are other iterator factory methods that can be used –
- keys() – returns an iterator that gives the index of the elements
- 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.
1 2 3 4 5 6 | var arr = ["coding", "raptor"]; var elem; var iter = arr.values(); while (!(elem = iter.next()).done) { console.log(elem.value); } |
In case the values() method does not work, you can try entries() as follows –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var iter = arr.entries(); while (!(elem = iter.next()).done) { console.log(elem); } /* Output: Object { value: Array[2], done: false } Object { value: Array[2], done: false } */ |
Similarly, it is quite straightforward to use the keys() iterator factory –
1 2 3 4 5 6 7 8 9 10 11 12 13 | var arr = ["coding", "raptor"]; var elem; undefined var iter = arr.keys(); while (!(elem = iter.next()).done) { console.log(arr[elem.value]); } coding raptor |
It’s quite straight forward to use the while loop –
1 2 3 4 5 6 7 8 9 10 | var website = ["Coding", "Raptor"]; var elem; var position = 0; while(elem = website[position++]) {console.log(elem); } // displays /* Coding Raptor */ |
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 –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // reusing the same website array // return value is another array that holds the modified values foreach element of the array var returnArray = website.map ( function(elem) { console.log(elem) ; } ); /* outputs Coding Raptor */ |
Conclusion/Quiz/Self Test
This post answered the following questions –
- What are arrays?
- How arrays in JavaScript differ from arrays in other programming languages?
- How to declare an array?
- How to manipulate individual elements of JavaScript array?
- 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.