An array in javascript is something that could be described as a list of values. Until now we've only talked about single values like strings and numbers that can be stored into variables. But sometimes you want to be able to store multiple values in the same place, like in a variable. For example if you wanted to store all names of the members of a club somewhere, it wouldn't really work to create a variable for every member.

It would instead be much better to have a great list containing all the names stored in just one variable. With arrays this is possible and they work just as one can expect. In javascript they're declared with two brackets as in the example below.

var arr = []; // Empty array
var names = ['john', 'bob', 'gus']; // Strings
var numbers = [1, 2, 3, 4, 5]; // Numbers
var mixed = [25, 'bob', true]; // Mixed

In some programming languages arrays are static, meaning their length is decided when they're first instantiated and can't then later be changed. If you first set the length to 10 and try to add in an 11th value into it, everything will crash. But in javascript arrays are dynamic, meaning values can be added and removed at any time. Their length is recalculated every time they change. You can actually set a specific length for them, but there's no real reason to do this since javascript sets it automatically.

Arrays are also not bound to any specific data type. So it's perfectly fine to have a mix of for example numbers, strings and booleans in them.

How to work with arrays

There are many different ways of working with arrays in javascript. Here we'll go through the most simple ways of declaring, manipulating and looping through them. Further down in this article we'll also check out a couple of their built in methods. But let's start with the basics.

var arr = [24, 33, 42];

console.log(arr[0]); // 24
console.log(arr[1]); // 33
console.log(arr[2]); // 42

arr[0] = 10; // Changes the first value in the array to 10
arr[3] = 55; // Adds the value 55 last in the array

console.log(arr[3]); // 55

console.log(arr[999]); // Undefined

An array is created by for example typing "var arr = [24, 33, 42]". Now we have created one containing three numbers and stored it in the variable arr. Arrays in javascript have a 0-based index so the first number (24) is retrieved by typing arr[0], arr[1] for the second number (33) and arr[2] for the last number (42). With this notation the values can also be changed and new values can be added at the end. For example by typing "arr[3] = 55" we add the number 55 to the end of it, and its length gets changed from 3 to 4. If trying to retrieve an index that doesn't exist in the array like arr[28] or something undefined is returned.

Loop through arrays

The previous chapter was about loops in javascript. As maybe noticed above the way of picking out every single value by hand quickly gets really time consuming. Instead we can use a loop to iterate through all their values and do something with them. In the example below all values of an array is printed out in the browser console. To know when the loop should finish the property "length" is used.

var names = ['john', 'bob', 'gus'];

console.log(names.length); // Prints the arrays length, 3

// Loops through the array and prints all names
for (var i = 0; i < names.length; i++) {
console.log(names[i]);
}

Methods

In javascript arrays have lots of built in methods for manipulating and extracting values from them in different ways. Except those below there was also a couple new ones introduced in ECMAScript 5. They are really useful and can be read about here at: ECMAScript 5 array methods.

Sort

var letters = ['d', 'e', 'c', 'a', 'b'];

letters.sort();
console.log(letters); // a, b, c, d, e

var numbers = [14, 10, 28, 5, 9];

// To sort numbers a special function must be added as argument
numbers.sort(function (a, b) {
return a - b;
});
console.log(numbers); // 5, 9, 10, 14, 28

Sort is a method in javascript that simply just sorts all the values in an array. Something a bit strange about it is it does it in an alphabetical order instead of numeric. To sort after numbers sort must be given a special function as argument. Change "a – b" to "b – a" for reverse order.

Reverse

var letters = ['a', 'b', 'c'];
letters.reverse(); // c, b, a

The method reverse is pretty straightforward and what it does is reversing the order of an array. For example it will reverse one containing the letters "a, b, c" to "c, b, a". Same with numbers. "1, 2, 3" gets reversed to "3, 2, 1".

Join, toString & toLocaleString

var names = ['john', 'bob', 'gus'];

console.log(names.toString()); // john,bob,gus

console.log(names.join(', ')); // john, bob, gus
console.log(names.join(' ')); // john bob gus
console.log(names.toString(' & ')); // john & bob & gus

Join is a simple and very useful method. It merges all values in an array to a string, separated after what argument its given. If no argument is given it merges the values with commas, just like the methods toString and toLocaleString does. The difference between toString and toLocaleString is that toLocaleString also includes some language specific characters that doesn't always work with toString.

Push, pop, unshift & shift

var letters = ['a', 'b', 'c'];

letters.pop(); // a, b
letters.push('d'); // a, b, d
letters.push('s', 'u'); // a, b, d, s, u


var numbers = [1, 2, 3];

numbers.shift(); // 2, 3
numbers.unshift(5); // 5, 2, 3

Push adds a value to the end of an array and pop removes the last, that's it. One difference is that push can take one ore more arguments for what values to be added at the end. Pop just removes the last value.

Unshift and shift works just like push and pop, except they add and remove values from the start instead.

Slice

var fruits = ['apple', 'pear', 'banana', 'orange'];

console.log(fruits.slice(1)); // pear, banana, orange
console.log(fruits.slice(2, 3)); // banana
console.log(fruits.slice(0, -1)); // apple, pear, banana
console.log(fruits.slice(0, 2)); // apple, pear

Slice does about what it sounds like. It "slices out" a portion of an array you don't want and returns it. It doesn't change the array directly like many of the other methods, instead it returns the new modified one and the old remains unchanged. The first argument is at what position the slice should start, and the second where it should end.

Splice

var numbers = [1, 2, 3, 4, 5];

numbers.splice(0, 2); // 3, 4, 5
numbers.splice(1); // 3

One could think that splice works just like slice. But not really, they have a few differences. Firstly splice changes the array directly and returns the removed part. Secondly the second argument is how many values should be removed, instead of to what position. It can also be given a third argument to also add new values at the same time.

Try it yourself

  1. Create an array and store it in a variable. Add the values 1, 2 and 3 to it.
  2. Loop through it and print out all values with console.log.
  3. Try out some of the array methods in javascript.