Arrays

JavaScript · Essentials · 10 min

Arrays are the everyday ordered collection for lists of anything.

An array is an ordered list of values of any types: const items = ["a", 2, { id: 3 }]. Indexes start at 0; items.length is the count, and items.at(-1) gets the last element.

Arrays are mutable objects. The core methods for adding and removing:

  • push(x) / pop() — add/remove at the end (fast).
  • unshift(x) / shift() — add/remove at the start (shifts every element).
  • splice(start, deleteCount, ...newItems) — remove and/or insert in the middle; mutates and returns removed items.
  • slice(start, end) — returns a copy of a portion, without mutating.

Searching: includes(x) returns a boolean, indexOf(x) returns the index or -1. Both compare by value for primitives but by reference for objects, so [{ id: 1 }].includes({ id: 1 }) is false. You'll use find with a callback for that in the array-methods lesson.

concat and join(sep) combine arrays and turn them into strings; Array.from({ length: 3 }, (_, i) => i) builds [0, 1, 2].

Because arrays are objects, assigning one to another variable copies the reference, not the elements: changing b after const b = a changes a too. Make a shallow copy with [...a] or a.slice().

typeof [] is "object"; use Array.isArray() to check. Assigning beyond the end (arr[10] = x on a short array) creates empty "holes" — avoid it. Arrays can be nested to make grids: grid[row][col].

Example

const queue = ["ann", "bob"];
queue.push("cy");               // [ 'ann', 'bob', 'cy' ]
const first = queue.shift();    // "ann"
console.log(first, queue);      // ann [ 'bob', 'cy' ]

const letters = ["a", "b", "c", "d", "e"];
console.log(letters.slice(1, 3));   // [ 'b', 'c' ]   (no mutation)
const removed = letters.splice(1, 2, "X");
console.log(removed, letters);      // [ 'b', 'c' ] [ 'a', 'X', 'd', 'e' ]

console.log(letters.includes("d"), letters.indexOf("z")); // true -1
console.log(letters.at(-1));        // "e"

const a = [1, 2];
const b = a;           // same array
const c = [...a];      // shallow copy
b.push(3);
console.log(a, c);     // [ 1, 2, 3 ] [ 1, 2 ]

Remember

  • Indexes start at 0; at(-1) reads from the end
  • slice copies, splice mutates — easy to mix up
  • Assigning an array copies the reference; copy with [...arr]

Watch out for

  • Expecting includes or indexOf to find an object by its contents — they compare references.

Check yourself

  1. const a = [1, 2, 3]; const b = a; b.push(4); — what is a.length?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array