JavaScript Arrays

In most programming languages, it is possible to store a list of values into a single container. In JavaScript, this container is known as an array. An arrayopen in new window is a comma-separated list of values, enclosed by a set of square brackets [].

Creating an Array

In JavaScript, an array is created with a set of square brackets ([]). When there is nothing in between the square brackets, this will create an empty array.

// Creates an empty array
const myEmptyArray = []

Items can be added to the array by inserting a comma-separated list between the square brackets.

// Creates an array of colors
const colors = ['blue', 'green', 'yellow', 'red', 'orange']

// Creates an array of numbers
const numbers = [1, 17, 8, 24]

// Creates a groceries list
const groceries = ['Apples', 'Milk', 'Ice Cream', 'Bread']

Retrieving Array Items

Each item in an array is assigned a numbered index. This index will be used to retrieve each item from the array.

NOTE

In JavaScript, like many other programming languages, arrays start with index 0, not 1.

To retrieve an item from an array, the variable name is followed by a set of square brackets ([]). Inside the square brackets is the numbered index of the desired item. This is known as Bracket Notation.

// Creates an array of colors
const colors = ['blue', 'green', 'yellow', 'red', 'orange']

// Logging the FIRST color in the colors array
console.log(colors[0]) // blue

// Logging the THIRD color in the colors array. 
console.log(colors[2]) // yellow

If a requested index is not in the array, the value undefined will be returned.

// Creates a groceries list
const groceries = ['Apples', 'Milk', 'Ice Cream', 'Bread']

// Logging an item that is not defined 
console.log(groceries[4]) // undefined

Updating Array Items

Just as variables can be assigned values, so can the items of an array. Items can be added or replaced using the Bracket Notation and the assignment operator (=).

// Creates a groceries list
const groceries = ['Apples', 'Milk', 'Ice Cream', 'Bread']

// Replaces the FIRST item in the groceries array
groceries[0] = 'Bananas' // groceries = ['Bananas', 'Milk', 'Ice Cream', 'Bread']

// Replaces the THIRD item in the groceries array 
groceries[2] = 'Yogurt' // groceries = ['Bananas', 'Milk', 'Yogurt', 'Bread']

// Adds an item to the groceries array
groceries[4] = 'Carrots' // groceries = ['Bananas', 'Milk', 'Yogurt', 'Bread', 'Carrots']

NOTE

While possible, it is discouraged to use Bracket Notation for adding new items to an array. It is better to use Array methods like push() or unshift().

This YouTube video was created by Steve Griffith.