Over a million developers have joined DZone.

Get Started With JavaScript Arrays

Here is an introduction into arrays, why to use them, and how to implement them.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Practically all programming languages have an inbuilt array data type. JavaScript is no different. They store the data you need to run scripts for an application, which, from a developer’s perspective, means you’ll be writing less code, making you more productive. That’s why it’s worth knowing your way around them.

In this tutorial, taken from the second edition of Learning JavaScript Data Structures and Algorithms, by Loiane Groner we’ll take you through the key principles behind using arrays and show you how to put the theory into practice.

Why Should We Use Arrays?

Let’s consider that we need to store the average temperature of each month of the year of the city that we live in. We could use something similar to the following to store this information:

var averageTempJan = 31.9;
var averageTempFeb = 35.3;
var averageTempMar = 42.4;
var averageTempApr = 52;
var averageTempMay = 60.8;

However, this is not the best approach. If we store the temperature for only 1 year, we could manage 12 variables. However, what if we need to store the average temperature for more than 1 year? Fortunately, this is why arrays were created, and we can easily represent the same information mentioned earlier as follows:

averageTemp[0] = 31.9;
averageTemp[1] = 35.3;
averageTemp[2] = 42.4;
averageTemp[3] = 52;
averageTemp[4] = 60.8;

We can also represent the averageTemp array graphically:

Image title

Creating and Initializing Arrays

Declaring, creating, and initializing an array in JavaScript is as simple, as shown by the following:

var daysOfWeek = new Array(); //{1}
var daysOfWeek = new Array(7); //{2}
var daysOfWeek = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); //{3}

We can simply declare and instantiate a new array using the keyword new (line {1}). Also, using the keyword new, we can create a new array specifying the length of the array (line{2}). A third option would be passing the array elements directly to its constructor (line {3}).

However, using the new keyword is not best practice. If you want to create an array in JavaScript, we can assign empty brackets ([]),as in the following example:

var daysOfWeek = [];

We can also initialize the array with some elements, as follows:

var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

If we want to know how many elements are in the array (its size), we can use the lengthproperty. The following code will give an output of 7:

console.log(daysOfWeek.length);

Accessing Elements and Iterating an Array

To access a particular position of the array, we can also use brackets, passing the index of the position we would like to access. For example, let’s say we want to output all the elements from the daysOfWeek array. To do so, we need to loop the array and print the elements, as follows:

for (var i=0; i < daysOfWeek.length; i++){
  console.log(daysOfWeek[i]);
}

Let’s take a look at another example. Let’s say that we want to find out the first 20 numbers of the Fibonacci sequence. The first two numbers of the Fibonacci sequence are 1 and 2, and each subsequent number is the sum of the previous two numbers:

var fibonacci = []; //{1}
fibonacci[1] = 1; //{2}
fibonacci[2] = 1; //{3}
for(var i = 3; i < 20; i++){
  fibonacci[i] = fibonacci[i-1] + fibonacci[i-2]; ////{4}
}
for(var i = 1; i < fibonacci.length; i++){ //{5}
  console.log(fibonacci[i]);           //{6}
}
  • So, in line {1}, we declared and created an array.
  • In lines {2} and {3}, we assigned the first two numbers of the Fibonacci sequence to the second and third positions of the array (in JavaScript, the first position of the array is always referenced by 0, and as there is no 0 in the Fibonacci sequence, we will skip it).
  • Then, all we have to do is create the third to the twentieth number of the sequence (as we know the first two numbers already). To do so, we can use a loop and assign the sum of the previous two positions of the array to the current position (line {4}, starting from index 3 of the array to the 19th index).
  • Then, to take a look at the output (line {6}), we just need to loop the array from its first position to its length (line {5}).

We can use console.log to output each index of the array (lines {5} and {6}), or we can also use console.log(fibonacci) to output the array itself. Most browsers have a nice array representation in the console.

If you would like to generate more than 20 numbers of the Fibonacci sequence, just change the number 20 to whatever number you like.

Adding Elements

Adding and removing elements from an array is not that difficult, however, it can be tricky. For the examples we will use in this section, let’s consider that we have the following numbers array initialized with numbers from 0 to 9:

var numbers = [0,1,2,3,4,5,6,7,8,9];

If we want to add a new element to this array (for example, the number 10), all we have to do is reference the latest free position of the array and assign a value to it:

numbers[numbers.length] = 10;

In JavaScript, an array is a mutable object. We can easily add new elements to it. The object will grow dynamically as we add new elements to it. In many other languages, such as C and Java, we need to determine the size of the array, and if we need to add more elements to the array, we need to create a completely new array; we cannot simply add new elements to it as we need them.

Using the push Method

However, there is also a method called push that allows us to add new elements to the end of the array. We can add as many elements as we want as arguments to the push method:

numbers.push(11);
numbers.push(12, 13);

The output of the numbers array will be the numbers from 0 to 13.

Inserting an Element in the First Position

Now, let’s say we need to add a new element to the array and would like to insert it in the first position, not the last one. To do so, first, we need to free the first position by shifting all the elements to the right. We can loop all the elements of the array, starting from the last position + 1 (length) and shifting the previous element to the new position to finally assign the new value we want to the first position (-1). Run the following code for this:

for (var i=numbers.length; i>=0; i--){
  numbers[i] = numbers[i-1];
}
numbers[0] = -1;

We can represent this action with the following diagram:

Using the unshift Method

The JavaScript array class also has a method called unshift, which inserts the values passed in the method’s arguments at the start of the array:

numbers.unshift(-2);
numbers.unshift(-4, -3);

So, using the unshift method, we can add the value -2 and then -3 and -4 to the beginning of the numbers array. The output of this array will be the numbers from -4 to 13.

Removing Elements

So far, you have learned how to add values to the end and at the beginning of an array. Let’s take a look at how we can remove a value from an array.

To remove a value from the end of an array, we can use the pop method:

numbers.pop();

NB: The push and pop methods allow an array to emulate a basic stack data structure.

The output of our array will be the numbers from -4 to 12. The length of our array is 17.

Hopefully, you’ve now got a solid understanding of how to make use of JavaScript arrays – put it into practice and see how much of an impact it has on the way you develop.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
javascript ,arrays

Published at DZone with permission of Joseph Zimmerman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}