Javascript Arrays Tutorial

In this Javascript tutorial we learn how to store multiple values within a single data container with arrays.

We learn how to initialize an array literal, how to create an array with its constructor, how to change array elements, and how to access array single array elements and multiple array elements in a loop.

We also cover some of the useful array functions to add and remove array elements.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is an array

An array is a data container that can store multiple separate values of the same type.

There are three ways to create an array in Javascript:

  • Array literal
  • Array instance (object)
  • Array constructor

How to initialize an array literal with []

The easiest, and most straightforward, way to create an array is by initializing an array literal.

To create an array literal, we start with a unique name, followed by the assignment operator and open and close square brackets ( [ ] ). Inside the square brackets we add one or more values, separating them with a comma.

Syntax:
var array_name = [value_1, value_2, ...];
Example:
<script>
  // array of strings
  var employee = ["John", "Jane", "Jack", "Jill"];
  //array of numbers
  var fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];
</script>

It’s like a table with a single row, but multiple columns.

JohnJaneJackJill

How to access array elements with the indexer

To access an array element (a single value in the array), we use the indexer.

When we create an array, each value is assigned to a corresponding number, its index. If we think about an array as a table, we would add another row with numbers, starting at 0.

0123
JohnJaneJackJill

These numbers form the index. When we want to access a specific element, we provide the translator with that element’s corresponding index number.

It’s important to note that any collection with a numerical index, will always start at 0, not at 1.

To use the indexer, we simply add the index number between square brackets, after the array name.

Syntax:
array_name[2];
Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  document.write( employee[2] );

</script>

In the example above, we access element number 2 in the array. Because the index starts at 0, it prints the third element “Jack” on the page.

How to access array elements with a loop

Arrays typically have many values and so it makes more sense to access values within a loop.

To use an array inside a loop, we have to use a counter as the index. Let’s see an example with a while loop, then break it down.

Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];
  var i = 0;

  while(employee[i]) {

    document.write(employee[i], "<br>");
    i++;
  }

</script>

We’ll use the variable i as the counter. We start by assigning the value 0 to the counter, because arrays start at 0. Then, in the body of the while loop, we increment the counter by 1.

This means we would start at the first element of the array, element 0, and continue to 1, 2, 3 etc. as the loop runs.

The while loop is nice for an array because we can just increment the counter in the condition. When the loop sees that there are no more elements in the array, the condition becomes false and the loop stops.

In a for loop, we would have to specify the amount of elements in the array explicitly.

Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  for(i = 0; i < 4; i++) {

    document.write(employee[i], "<br>");
  }

</script>

The problem with the for loop is that we may not know how many elements there are in an array beforehand.

Luckily, Javascript provides us with the built-in array.length property that figures it out for us. To use the property, we simply write the array name, followed by a dot operator ( . ) and the keyword length .

Syntax:
var array_name = [value_1, value_2, value_3];

// Get the amount of
// elements in array_name
array_name.length;
Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  document.write("There are ", employee.length, " employees");

</script>

Now all we need to do is use the length property in the condition of the for loop.

Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  for(i = 0; i < employee.length; i++) {

    document.write(employee[i], "<br>");
  }

</script>

The for loop is a safer option than the while loop because it’s guaranteed to loop only the amount of times there are elements in the loop.

How to change array elements

Changing array elements is simple, we use the indexer to specify the element and assign a new value to it with the assignment operator.

Syntax:
array_name[index] = new_value;
Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  document.write(employee[0], "<br>");

  // mutate element
  employee[0] = "John Doe";

  document.write(employee[0]);

</script>

In the example above, we change the name in the first array element from “John” to “John Doe”. The translator overwrites the previous value with the new one we provide.

How to add array elements

To add elements to an array, we use the built-in array.push() function. It will push a value onto the end of the array.

To push an element, we write the array name, followed by a dot operator and the push() function. Then, we specify the value we want to add as an argument.

Syntax:
array_name.push(value_to_add);
Example:
<script>

  var film_list = [

    "The Godfather",
    "Star Wars: Episode V",
    "The Dark Knight",
    "Pulp Fiction"
  ];

  // push element into array
  film_list.push("Back to the future");

  // print array to page
  document.write("Best movies of all time:<br><ol>");
  for (i = 0; i < film_list.length; i++) {

    document.write("<li>", film_list[i], "</li>");
  }
  document.write("</ol>");

</script>

In the example above, we push a single value into a new element at the end of the array.

We can push more than one element into the array by separating the values we want to push with a comma. The values will be added in the same order we specify in the push() function.

Syntax:
array_name.push(value_1, value_2, value_3);
Example:
<script>

  var film_list = [

    "The Godfather",
    "Star Wars: Episode V",
    "The Dark Knight",
    "Pulp Fiction",
    "Back to the future"
  ];

  // push multiple elements into array
  film_list.push("Alien", "Fight Club", "Die Hard", "Jarassic Park", "Inception");

  // print array to page
  document.write("Best movies of all time:<br><ol>");
  for (i = 0; i < film_list.length; i++) {

    document.write("<li>", film_list[i], "</li>");
  }
  document.write("</ol>");

</script>

In the example above, we add 5 more elements to the array. When we look at the list printed on the page, we can see that the elements were added in the same order we specified in the code.

How to remove array elements

Javascript provides us with three functions to remove elements from an array, depending on where the element is.

  • pop() - Removes an element from the end of the array.
  • shift() - Removes an element from the start of the array.
  • splice() - Removes an element at a specific index.

To remove an element from the end of an array, we use the array.pop() function without any arguments.

Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  // remove element from
  // the end of the array
  employee.pop();

  for (i = 0; i < employee.length; i++) {

    document.write(employee[i], "<br>");
  }

</script>

An added benefit is that the pop() function will return the value of the element which it just removed.

Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  // remove element from
  // the end of the array
  // and print to the page
  document.write( employee.pop() );

</script>

This is useful if you want to do something with the value before completely discarding it.

To remove an element from the start of an array, we use the array.shift() function, without any arguments.

It will work exactly the same as the pop() function, except for removing the element at the start instead of the end. It will also return the value that it removed.

Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  // remove element from
  // the start of the array
  document.write( employee.shift() );

</script>

If we want to remove an element at a specific index, or multiple elements, we use the array.splice() function.

This time, the function needs two arguments. The first argument specifies the index at which to begin removing elements. The second argument specifies the number of elements to remove.

Syntax:
array_name.splice(index, num_elements_to_remove);
Example:
<script>

  var employee = ["John", "Jane", "Jack", "Jill"];

  // remove element from
  // the start of the array
  document.write( employee.splice(2, 1) );

</script>

In the example above, we remove the element at index number 2, “Jack”. The array.splice() function also returns the element(s) it removed.

How to create an array instance

Because an array is an object, we can create a new array by instantiating it with either the new keyword, or the array constructor.

Syntax:
var array_name = new Array();

After the new array has been created, we can populate it with values via the indexer.

Example:
<script>

  var employee = new Array();

  employee[0] = "John";
  employee[1] = "Jane";
  employee[2] = "Jack";
  employee[3] = "Jill";

</script>

An easier way is to initialize the instance with values directly by using the array constructor. To use the constructor, we simply add the values we want between parentheses.

Syntax:
var array_name = new Array(value_1, value_2, value_3);
Example:
<script>

  var employee = new Array("John", "Jane", "Jack", "Jill");

</script>

Many developers feel that the extra typing is unnecessary and prefer to initialize an array with square brackets instead.

List of array object methods

Because an array is an object, Javascript provides us with handy functions to perform array specific operations.

FunctionDescription
concat()Merge two or more arrays and return the new array.
copywithin()Copy part of an array and return the new modified array.
every()Determine whether all elements in an array satisfy specific function conditions.
fill()Fill an array, or part of an array, with a single value.
filter()Return an array with the elements that satisfy specific function conditions.
find()Find the first occurance of a value in the array and return its value.
findIndex()Find the first occurance of a value in the array and return its index.
forEach()Calls a function for each element in the array.
includes()Checks if an array contains a specific element.
indexOf()Find the first occurance of a value in the array and return its index.
join()Join the elements of an array as a string.
lastIndexOf()Find the last occurance of a value in the array and return its index.
map()Calls a function for every array element and return the new array.
pop()Removes the last element of an array and return it.
push()Adds one or more elements to the end of an array.
reverse()Reverse the elements of an array.
shift()Removes the first element of an array and return it.
slice()Copy part of an array and return the new array.
sort()Return elements of an array in a specific sorted order.
splice()Adds or removes elements at a specific position in an array.
unshift()Add one or more elements to the start of an array.

Summary: Points to remember

  • An array is a data container that can store more than one value.
  • We initialize an array literal by providing it with multiple, comma separated, values between square brackets.
  • We instantiate an array with the new Array() constructor.
  • We access array elements with their corresponding index number between square brackets.
  • When we access elements in a loop, we need to provide a counter to move through the elements in the array.
  • A for loop is safer than a while loop because it’s guaranteed to run only the length of the array.
  • To change the value of a single element, we simply assign a new value to it.
  • Javascript provides us with many array specific methods to add, remove, copy, find elements etc. when working with arrays.