Arrays

Arrays are container-like values that can hold other values. The values inside an array are called elements.

Editable Code

var breakfast = ["coffee", "croissant"];

breakfast;

Array elements don’t all have to be the same type of value. Elements can be any kind of JavaScript value — even other arrays.

Editable Code

var hodgepodge = [100, "paint", [200, "brush"], false];

hodgepodge;

Accessing Elements

To access one of the elements inside an array, you’ll need to use the brackets and a number like this: myArray[3]. JavaScript arrays begin at 0, so the first element will always be inside [0].

Editable Code

var sisters = ["Tia", "Tamera"];

sisters[0];

To get the last element, you can use brackets and `1` less than the array’s length property.

Editable Code

var actors = ["Felicia", "Nathan", "Neil"];

actors[actors.length - 1];

This also works for setting an element’s value.

Editable Code

var colors = ["red", "yelo", "blue"];

colors[1] = "yellow";

colors;

Properties and methods

Arrays have their own built-in variables and functions, also known as properties and methods. Here are some of the most common ones.

length

An array’s length property stores the number of elements inside the array.

Editable Code

["a", "b", "c", 1, 2, 3].length;

concat

An array’s concat method returns a new array that combines the values of two arrays.

Editable Code

["tortilla chips"].concat(["salsa", "queso", "guacamole"]);

pop

An array’s pop method removes the last element in the array and returns that element’s value.

Editable Code

["Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"].pop();

push

An array’s push method adds an element to the array and returns the array’s length.

Editable Code

["John", "Kate"].push(8);

reverse

An array’s reverse method returns a copy of the array in opposite order.

Editable Code

["a", "b", "c"].reverse();