CPCODELAB
JavaScript

Arrays and Core Array Methods

11 min read

Arrays

Arrays are ordered, zero-indexed lists that can hold any mix of types. They are objects under the hood, so typeof [] returns "object". Use Array.isArray() to check.

javascript
const nums = [1, 2, 3, 4, 5];

nums.length;         // 5
nums[0];             // 1 (first)
nums[nums.length-1]; // 5 (last)
nums.at(-1);         // 5 (ES2022 negative index)

// Mutating methods
nums.push(6);        // adds to end    → [1,2,3,4,5,6]
nums.pop();          // removes from end
nums.unshift(0);     // adds to start  → [0,1,2,3,4,5]
nums.shift();        // removes from start

// splice(start, deleteCount, ...items)
nums.splice(2, 1);   // removes 1 element at index 2
nums.splice(2, 0, 99); // inserts 99 at index 2

Non-Mutating Methods

javascript
const arr = [1, 2, 3, 4, 5];

arr.slice(1, 3);       // [2, 3] (end index excluded)
arr.concat([6, 7]);    // [1,2,3,4,5,6,7]
arr.join(" - ");        // "1 - 2 - 3 - 4 - 5"
arr.includes(3);       // true
arr.indexOf(3);        // 2
arr.lastIndexOf(3);    // 2
arr.reverse();         // mutates! use [...arr].reverse()
arr.flat();            // flattens one level
arr.flat(Infinity);    // deeply flatten
Array.from({ length: 3 }, (_, i) => i); // [0,1,2]

Prefer non-mutating approaches when working with state. Instead of arr.reverse(), use [...arr].reverse() or arr.toReversed() (ES2023) to get a new reversed array without touching the original.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises