Arrays: An Introducion

Creating arrays in JavaScript, populating them with elements, reading and updating array elements, and looping through arrays.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Create and populate an array.
  • Find the length of an array.
  • Use array indexes to read and modify values in an array.
  • Loop through all the values in an array.

Working with Arrays: JS Code Snippets

Arrays: when variables are not enough

A variable, as you have learnt, can store a value. Think of a variable as a ‘box’ in which you can place a single value. See below.

Variable with a single value

But suppose you want to store several values in a ‘box’? You need a different kind of variable; you need an array.

Below you can see an array or multi-compartment ‘box’ that contains four values or elements (also called items).

Array with multiple values

Each array element has an identifying integer (whole number) known as an index. Indexes begin at zero and the number is written inside square brackets [].

Array indexes

For example, an array with four elements has the following indexes: [0], [1], [2] and [3]. JavaScript arrays are said to be zero-indexed.

Arrays in JavaScript are not primitives but a special type of object. The typeof operator when applied an array will return "object".

Array

The Array object enables a collection of mutable items to be stored and manipulated with a single variable name. Arrays are iterable (can be looped through), resizable (elements can be added/removed), can contain a mix of different data types, and are zero-indexed. An array with n elements is indexed from 0 to n-1.

The benefit of using arrays is that you can work with datasets with just a single name and an index number. For example, instead of assigning the twelve months of the year to twelve different variables, you could assign them to a single array.

Naming your arrays

As with variable names, there are rules for naming arrays.

  • Do not use the same name for two different arrays within the same scope.
  • Do not insert spaces within array names.
  • Make long array names easier to read by using camelCase.
  • Remember that array names are case-sensitive: bestArrayEver is not the same as bestarrayEver.

Array naming conventions

There are a number of coding conventions (‘soft rules’) for naming arrays:

  • It is common to pluralize array names, such as products rather that product and users rather than user.
  • Some developers begin array names with arr, such as arrStudents and arrEmployees.
  • In the Google Style Guide you will see arrays with names such as moduleLocalArray and exportedArray.

Your JavaScript code will be easier to read if you name your arrays in a diferent way to regular (single-value) variables.

Creating an array

You can create an array in either of two ways

  • Array literal: This is the recommended method. See sample below.
     const users = ["Bridget","Carol","Christine","Deborah"];  
  • Array constructor: See below. This is not recommended.
     const users = new Array ("Bridget","Carol","Christine","Deborah");  

Both methods create exactly the same array and both use the square bracket [] syntax.

It is better to use const rather than let when creating arrays. This prevents you from accidentally overwriting an array with the same name that might already exist elsewhere in the same scope. If you do, JavaScript will throw on error.

Array name already declared

Using the const keyword does not prevent your code from modifying elements in an array as needed. Array elements are always mutable. It just means the array name cannot be reassigned in the same scope of your program.

Populating an array

With regular (single-value) variables, you can declare (create) them in one statement and later initialise (assign a value) to them in another statement.See below.

 let varFood;
 console.log(varFood);
 // returns nothing to console
 varFood = "cheese";
 console.log(varFood);
 // returns "cheese"

Alternatively, you can both declare and initialise a variable in a single statement.

 const varDrink = "green tea";
 console.log(varDrink);
 // returns "green tea"

The same is true with declaring array variables. The following statement creates an empty array.

 // create empty array
 const arrMeals[];
 console.log(arrMeals);
 // returns nothing to console

Here are two examples of declaring and assigning values to an array in a single statement. Initialising an array is called populating the array.

 const arrPrices = [11.99, 24.50, 34.25, 49.99];
 const arrCars = ["Volvo", "Citreon", "BMW", "Opel", "Peugeot", "Ford"];

Individual array elements are separated by commas. Strings are typically wrapped with double "" rather than single quotes ''.

Optionally, for extra readability, spaces may be included along with commas. For the same readability reason, you may sometimes see array declarations written over multiple lines as follows.

 const arrUserIDs = [
   4032,
   5229,
   6317,
 ];

As you can see above, there is a ‘trailing comma’ , after the final element 6317. Developers sometimes add an optional trailing comma to the final element of an array or object. This makes all lines look alike and can make it easier to insert/remove elements later.

One array: multiple data types

In JavaScript elements in an array need not to be same data type. See below.

 const arrMixed = ["Movie title", 15.99, 2012, null, true];

An array can contain strings, numbers, functions, objects – even other arrays. An array that contains another array is called a multi-dimensional array.

Unless you have a very good reason to do so, it is not recommended to mix multiple data types in your arrays.

The length of an array

Every array has a length property that reveals the number of elements in the array. The syntax is as follows.

 array_name.length

The following example will output an array length of 5 to the console.

 const arrFruits = ["Apple","Banana","Blueberry","Pear","Lemon"];
 console.log("Number of items in arrFruits: "+arrFruits.length);
 // returns 5

Remember: the length of an array is always one number greater than the array's highest index number.

Reading array contents

How do you read what’s stored in an array? There are two situations when you want to access or ‘get at’ array values:

  • When you want to write the values to the browser window, perhaps with a document.write() statement.   The following example writes the 34th index value from the array named email_addr to the browser window.
      document.write(“Email Address: "+email_addr[34]+"<br>");
    
  • To copy an element’s value to regular (single-value) variable, use an assignment statement such as the one shown below.
      let customer21_id = customer_ids[21];
    
    In the above example, the value of the 21st element in the array named customer_ids is copied to the variable named customer_21. The array remains unchanged.

Here is the syntax for reading the last element in an array.

console.log("Last element:"+ fruits[fruits.length - 1]);

Looping through an array with for ... next

Suppose your script contains an array named fruits with six elements. You could write the values of the array‘s six elements to the browser console with six separate console.log() statements as shown below.

 console.log("Array Element 0: "+fruits[0]);
 console.log("Array Element 1: "+fruits[1]);
 console.log("Array Element 2: "+fruits[2]);
 console.log("Array Element 3: "+fruits[3]);
 console.log("Array Element 4: "+fruits[4]);
 console.log("Array Element 5: "+fruits[5]);

That's a lot of typing.

There is an easier way: use a for...next loop containing a single console.log() statement as shown below.

for (i = 0; i <= 5; i++) {
   console.log("Array Element "+i+": "+fruits[i]);
}

As you can see, there are six elements in the array. However, the initial value of the counter variable i is set to 0 and the upper value is set to 5.

This is because the array's index numbering runs from [0] to [5] and not from [1] to [6].

To use a for...next loop to access all the values from an array, follow this simple rule:

The number of loop iterations must be the same as the number of elements in the array.

That way a console.log() statement is performed for each individual array element.

But the number of array elements may change during the script, so how can you set the upper value for the counter variable?

The solution is to use the array length property as the upper limit of a for...next loop as follows.

for (i = 0; i < fruits.length; i++) {
  console.log("Looping with for ... next: "+fruits[i]);
}

Notice that the comparison operator for the upper value of the counter variable is 'less than' (<) and not 'less than or equal to' (<=).

Why?

Because the array length is always one greater than the index number of the highest array element.

For example, When an array has six elements, its index numbers run from [0] to [5], and its length property contains the value of 6.

Looping through an array with for ... of

There is an even easier way to loop through the values of an array: the for...of loop. See the example below.

for (element of arrFruits) {
  console.log(element);
}

Looping through an array with forEach

A third option is to use the forEach loop. See the example below.

arrCars.forEach(element => console.log(element));

Updating array values

Up to now, you have populated array elements only at the time you created the array. But you can insert values into an array at any stage. The general syntax is as follows.

array_name[index_number] = element_value;

The following code assigns the number 34 to the 20th index position of the array named myArray.

myArray[20] = 34;

You don't need to populate array elements in consecutive order, as in [0], [1], [2], [3], [4] and so on.

Imagine that you have an array called userNames. It contains 10 elements, indexed from [0] to [9]. The following three statements are all valid.

userNames[10] = "Murphy";
userNames[11] = "Jones";
userNames[20] = "Collins";

In other words, JavaScript allows you to have ‘gaps’ or unfilled elements in an array. An array with such non-contiguous values is said to be sparsely populated. JavaScript treats the value of an unfilled array element as undefined.

Modifying array values

You change the value of an array element in exactly the same way as you first assign a value to that element. If your userNames array currently has values at index locations [8], [9] and [56], the following statements overwrite those values with the new ones.

userNames[8] = "Harper";
userNames[9] = "Wallace";
userNames[56] = "Johnson";

Deleting array values

You can remove the contents of an array element with the delete method.

delete userNames[67];

This does not actually delete the element from the array; it just sets its value as undefined. The length property of the array is unaffected.

This way of deleting an element from an array is not recommended.