Super Javascript
Home About RSS Guest Blogging

JavaScript Arrays

JavaScript Arrays

Is one of anything ever enough? If not then you might need an array. Arrays are how you represent lists in a JavaScript program.

Lists appear everywhere in the apps we build: search results, contact lists, Spotify playlists, tweets and so on. This makes arrays one of the most taken for granted tools that programmers use every day.

In JavaScript, arrays can have zero or more items, and each item can be any object or value, such as a string, a number, another array or an object. There are many powerful JavaScript functions available to make JavaScript arrays and modify them. We’ll take a look at all of this in more detail as we get to know JavaScript Arrays in this tutorial.

A quick note about ES6

The examples in this tutorial use the version of JavaScript referred to as ES6. This JavaScript version came out in 2015 and is compatible with modern browsers, for example up, to date versions of Edge, Chrome, Firefox, Safari, Opera, and Android.

It is, in my opinion, the best version to learn at the moment. However if you ever need to write code that works on Internet Explorer or older browsers, you can get free tools such as Babel that will convert ES6 to older versions of JavaScript that will run on those browsers if you require this.

How to create a JavaScript Array

To create an array in JavaScript you put the list of things separated by commas in square brackets, for example, if you want an array with the numbers 1 to 10 you create it like this:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

You can also create an empty array. This might seem like an odd thing to do. However this is useful in situations when you start off not knowing what is going to go in your array, but you can add items to the array later.

For example, as somebody types on their keyboard, the letters could be added to an array. At the beginning of the program, nothing has been typed yet so the array is empty.

You create an empty JavaScript array like this:

let arr = [];

An array can contain different things. Or more accurately: different types. You can chuck in a number in an array, followed by a string, then an object and so on. Here is an example:

const arr = [1, "2", true, { message: 'hello' }];

This means when you work with arrays that have come from unfamiliar places, you need to know what to expect, and possibly handle unexpected types. If you get a list of names, is it all strings, or might there be a number lurking in there? If there is a number, what will your program do? It is always good to test these cases.

Getting items out of a JavaScript array

For an array to be useful you need to be able to get the items out of the array. There are a few ways to do this, the simplest is to get the elements by index.

The index is the position of the item in the array. In normal life, we count from 1. In programming life, we count from 0. This means the first index is 0, then 1, 2 etc.

For example, the code below will get the first index of the array, which is 3. It does this by putting the index in square brackets after the array name:

let arr = [3,2,1];
const result = arr[0];

The index can also be a variable. This allows you to ‘loop through’ an array to visit all of its contents using a for statement. Have a quick look at the example below and then I’ll explain it:

let arr = [3,2,1];
for (let i=0; i<arr.length; i++) {
    console.log(arr[i]);
}

In the code above, the for statement will run the code inside the braces { and } multiple times, each time setting i to a different value. The first time it is 0, then 1, then finally 2.

The statement inside the braces will look up the item at index i and show this to the console log. The console log is used by programmers to see what a program is doing.

Feel free to read more about JavaScript For and Console Logging, if this doesn’t make sense, or if you want to know more about the mechanics of the for loop.

If you run this code you will see the following result:

 3
 2
 1

Adding items to an array

Using the push function

There are a few ways to add items to an array in JavaScript. Perhaps the simplest is a function called push which is a function on the array (called a prototype function). To see how this works look at the following code:

let arr = [];
arr.push(3);
console.log(arr);

This will create an empty array and then add the value 3 to the end of that array, and show the following result:

[3]

Using the splice function

The push function is great, but what if you want to add an item to the beginning or middle of an array? Well JS has you covered. You can use the splice function to do this. This is a powerful function that can do a few things so it will need a bit of explaining.

In the next example I will add an item 'charles' in the third position, which is index 2. Here it is:

let arr = ['Adam', 'Ben', 'Douglas'];
arr.splice(2, 0, 'Charles');
console.log(arr);

Result:

['Adam', 'Ben', 'Charles', 'Douglas']

Splice takes 3 arguments:

  1. The first is the index within the array that you would like to add items. We passed in 2 to mean the 3rd item.
  2. The second is the number of items to remove at that position. We have set this to 0 to avoid deleting anything from the array.
  3. The last argument is the item or items to add to the array at that position. We only want to add 'Charles' so we pass just that one value.

Splice is a fantastic function and can do more than just insert items into an array. You can also use it to remove items or replace items. There will soon be a page on javascript splice, so watch this space if you fancy learning more. In the meantime see Mozilla’s Developer Site is your friend for more information.

Mapping Arrays

Sometimes you need to do something to every item in an array. For example, you might want to turn a list of names into a list of greetings, replacing say “Harold” with “Hello Harold”.

The traditional way of doing this is to use a for loop, which allows you to run through the numbers from zero to the last index of the array. Each time the loop is run you get the item from the array, add your 'Hello ', and then store it either in the same array or a new array.

Mapping gives you a convenient shortcut for this. The array function map will run a function on every item of the array and returns a new array with those new results. It doesn’t make any modifications to the original array.

Here is an example:

let names = ['Harold', 'Judy', 'Declan'];
let greetings = names.map(function(name) {
	return 'Hello ' + name;
})
console.log(names);
console.log(greetings);

The first result from console.log(names) shows that the names are unchanged:

["Harold", "Judy", "Declan"]

The second result from console.log(greetings) shows that the new greetings array contains what you would expect:

["Hello Harold", "Hello Judy", "Hello Declan"]

The argument passed to the map function is a function itself, let’s look at that a bit more closely:

function(name) {
	return 'Hello ' + name;
}

What this function does is take in a name, which it expects to be a string, and appends the text 'Hello ' to the beginning and returns that new string.

Removing Elements

Using delete

The delete keyword will remove an item from an array, leaving a ‘hole’ behind. Using the names example again, we can do something like this:

let names = ['Harold', 'Judy', 'Declan'];
delete names[1];
console.log(names);
console.log(names[1]);

The result is:

["Harold", empty, "Declan"]

undefined

What happened is the item is deleted but the space it occupied still remains. The index of every other item stays as it was, and where the deleted item used to be is replaced with empty. The second result shows that when you look up that item in the array, it will return undefined.

Using splice

If you instead want to remove the element and not leave a hole, you can use splice like this:

let names = ['Harold', 'Judy', 'Declan'];
names.splice(1, 1)
console.log(names);
console.log(names[1]);

We met splice earlier to add elements, so let’s recap on that.

The first argument is the index. The second argument is the number of items to remove. So we are saying remove 1 item from index 1. Or in simple terms, remove poor old Judy.

The result is:

["Harold", "Declan"]
Declan

Notice how there is no third argument this time to splice. This is because we don’t want to add anything, and JavaScript doesn’t demand that you pass in all of the arguments. If you pass in fewer arguments, it will treat the missing ones as undefined.

Summary

This tutorial provides a basic grounding in Arrays covering the most common ways in which you will use them in a JavaScript program.

There are lots of other functions for Arrays, which you can research by exploring the Mozilla Developer Site and eventually I will add more in-depth articles about arrays on SuperJavaScript.

Thanks for reading, and good luck.

While you are here...

You like retro? I'm working on a guide where I will take you step by step to make a classic arcade game in JS. I can't wait to show it you.

There will be lots of opportunities to add your creative flair and make it truly your game. The guide will be free. If you want to be updated on the release of this book, just enter your email below:

Thanks!

See Also