<htmlstart/>

JS Arrays

Arrays store ordered lists of values and come with powerful built-in methods.

Creating Arrays

const fruits   = ["apple", "banana", "cherry"];
const numbers  = [1, 2, 3, 4, 5];
const mixed    = ["hello", 42, true, null];  // any types
const matrix   = [[1,2], [3,4], [5,6]];      // nested arrays

// Access by index (starts at 0)
fruits[0]   // "apple"
fruits[2]   // "cherry"
fruits.at(-1) // "cherry" — last item (ES2022)

Add / Remove

const arr = [1, 2, 3];

arr.push(4);      // add to end    → [1, 2, 3, 4]
arr.pop();        // remove from end → [1, 2, 3]
arr.unshift(0);   // add to start  → [0, 1, 2, 3]
arr.shift();      // remove from start → [1, 2, 3]

// splice(startIndex, deleteCount, ...itemsToInsert)
arr.splice(1, 1);        // remove 1 item at index 1 → [1, 3]
arr.splice(1, 0, 10, 11); // insert without removing → [1, 10, 11, 3]

Essential Array Methods

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

// map — transform each item
nums.map(x => x * 2);         // [2, 4, 6, 8, 10]

// filter — keep items matching condition
nums.filter(x => x > 2);      // [3, 4, 5]

// find — first matching item
nums.find(x => x > 3);        // 4

// reduce — accumulate to single value
nums.reduce((sum, x) => sum + x, 0);  // 15

// some / every
nums.some(x => x > 4);        // true  (at least one)
nums.every(x => x > 0);       // true  (all)

// includes
nums.includes(3);              // true

// sort
["banana","apple","cherry"].sort(); // ["apple","banana","cherry"]
[3,1,2].sort((a,b) => a - b);      // [1, 2, 3] — numeric sort

// join / split
["a","b","c"].join("-");       // "a-b-c"
"a-b-c".split("-");            // ["a","b","c"]

// spread
const copy    = [...nums];
const merged  = [...nums, 6, 7];
map, filter, and reduce are the three most important array methods. Master them and you can solve most data transformation problems without writing explicit loops.
🧩

Test Yourself

4 questions
Q1.Which method adds an element to the END of an array?
Q2.Which array method creates a NEW array with transformed elements?
Q3.What does filter() return?
Q4.What does [3,1,2].sort((a,b) => a - b) produce?