JavaScript by Example

Arrays

Ordered lists of values, zero-based indexes, length, push, pop, and the mutation rule beginners need first.

An array is an ordered list of values. Each value sits at a numbered position called an index, starting at 0. You can store any mix of values, but in practice most arrays hold one type of thing.

Create an array with square brackets. Read a value by writing the array name followed by its index in brackets. .length tells you how many elements are in the array.

const fruits = ["apple", "banana", "cherry"];
 
console.log(fruits[0]); // "apple"   (first element)
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "cherry"  (last element)
 
console.log(fruits.length); // 3

push adds an element to the end of the array. pop removes and returns the last element. Both change the original array in place.

const fruits = ["apple", "banana"];
 
fruits.push("cherry");
console.log(fruits); // ["apple", "banana", "cherry"]
 
const last = fruits.pop();
console.log(last);   // "cherry"
console.log(fruits); // ["apple", "banana"]

In production

Array methods differ on mutation. push, pop, and sort change the original array. Methods like map, filter, and slice return a new array. Know which kind you are calling before updating shared state.

Enjoyed this? Get more software craft delivered to your inbox.