14: Working with Arrays

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

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.

In your javascript/exercises folder, create a new sub-folder named arrays-intro.

Save the exercise file below to this new javascript/exercises/arrays-intro sub-folder.

Introduction to Arrays: Exercises

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 with the array literal syntax as follows:

const users = ["Camille","Emma","Gabriel","Romy"];
const arrPrices = [11.99, 24.50, 34.25, 49.99];
const arrCars = ["Volvo", "Citreon", "BMW", "Opel", "Peugeot", "Ford"];

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.

screenshot

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.

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];

But it is not recommended to mix multiple data types in your arrays.

The .length property 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.

console.log(`The length of arrFruits array: ${arrFruits.length}`);

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 log a value to verify your code is running correctly. For example.
      console.log(`The item at index position 3 in arrFruits array: ${arrFruits[3]}`);
  • To copy an element’s value to regular (single-value) variable, use an assignment statement such as the one shown below.
      let strFruit0 = arrFruits[0];
    console.log(`Element from 0th position of array now in variable strFruit0: ${strFruit0}`);
    In the above example, the value of the 0th element in the arrFruits array is copied to the string variable named strFruit0. The array remains unchanged.

And here is the syntax for reading the last element in an array.

console.log(`Last element of arrFruits array: ${arrFruits[arrFruits.length - 1]}`);

About array destructuring

Array destructuring enables developers to unpack values from arrays and assign them to variables in a more concise and readable manner.

Basic array destructuring

Suppose you have the following array:

const colors = ["red", "green", "blue"];

Without destructuring, if you wanted to assign these colors to individual variables, you would do:

const firstColor = colors[0];
const secondColor = colors[1];
const thirdColor = colors[2];

With array destructuring, this can be simplified to:

const [firstColor, secondColor, thirdColor] = colors;

Here, firstColor will be "red", secondColor will be "green", and thirdColor will be "blue".

Skipping items in an array

You can skip items in the array if you're only interested in certain values:

const [firstColor, , thirdColor] = colors;

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.

 

 Back to Top