Skip to main content

Arrays

An array is a special variable that can hold more than one ordered value at a time. Arrays use zero-based indexing.

Creating Arrays

// Array Literal (Most common and preferred)
const fruits = ["Apple", "Orange", "Plum"];

// Array Constructor
const years = new Array(2020, 2021, 2022);

Because arrays are Objects in JavaScript, they can hold vastly different data types inside the same array (although it's generally best practice to keep arrays cohesive).

const mixed = ["String", 100, true, null, { name: "Bob" }];

Accessing & Mutating Arrays

You access elements inside an array utilizing bracket notation [] and their index.

const cars = ["Honda", "Toyota", "Ford"];

console.log(cars[0]); // Honda
console.log(cars[2]); // Ford

// Reassigning
cars[1] = "Subaru";
console.log(cars); // ["Honda", "Subaru", "Ford"]

Basic Array Properties & Methods

Arrays come with powerful, built-in properties attached to their prototype.

const numbers = [10, 20, 30];

// Length property tracks size
console.log(numbers.length); // 3

// Adding to the end: push()
numbers.push(40); // [10, 20, 30, 40]

// Removing from the end: pop()
numbers.pop(); // Returns 40. Array becomes [10, 20, 30]

// Adding to the front (shifts elements over): unshift()
numbers.unshift(0); // [0, 10, 20, 30]

// Removing from the front: shift()
numbers.shift(); // Returns 0.