Arrays are container-like values that can hold other values. The values inside an array are called elements.
// EXAMPLE
var breakfast = ["coffee", "croissant"];
breakfast;
// OUTPUT
["coffee", "croissant"]
Array elements don’t all have to be the same type of value. Elements can be any kind of JavaScript value — even other arrays.
// EXAMPLE
var hodgepodge = [100, "paint", [200, "brush"], false];
hodgepodge;
// OUTPUT
[100, "paint", [200, "brush"], false]
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].
// EXAMPLE
var sisters = ["Tia", "Tamera"];
sisters[0];
// OUTPUT
"Tia"
To get the last element, you can use brackets and `1` less than the array’s length property.
// EXAMPLE
var actors = ["Felicia", "Nathan", "Neil"];
actors[actors.length - 1];
// OUTPUT
"Neil"
This also works for setting an element’s value.
// EXAMPLE
var colors = ["red", "yelo", "blue"];
colors[1] = "yellow";
colors;
// OUTPUT
["red", "yellow", "blue"]
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.
// EXAMPLE
["a", "b", "c", 1, 2, 3].length;
// OUTPUT
6
concat
An array’s concat method returns a new array that combines the values of two arrays.
// EXAMPLE
["tortilla chips"].concat(["salsa", "queso", "guacamole"]);
// OUTPUT
["tortilla chips", "salsa", "queso", "guacamole"]
pop
An array’s pop method removes the last element in the array and returns that element’s value.
// EXAMPLE
["Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"].pop();
// OUTPUT
"Pluto"
push
An array’s push method adds an element to the array and returns the array’s length.
// EXAMPLE
["John", "Kate"].push(8);
// OUTPUT
3
reverse
An array’s reverse method returns a copy of the array in opposite order.
// EXAMPLE
["a", "b", "c"].reverse();
// OUTPUT
["c", "b", "a"]