Arrays — Create, Modify & Transform
Arrays hold ordered lists: const arr = [1, 2, 3]. Index starts at 0 — arr[0] is first item.
Creating and Indexing Arrays
Arrays hold ordered lists: const arr = [1, 2, 3]. Index starts at 0 — arr[0] is first item.
Real-life example: A numbered queue at a ticket counter — position 0 is first in line.
const colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors.length); // 3push, pop, shift, unshift
push adds to end. pop removes from end. shift removes from start. unshift adds to start.
Real-life example: push/pop — people joining or leaving the back of a line. shift/unshift — front of the line.
const list = ["a", "b"];
list.push("c"); // ["a","b","c"]
list.pop(); // removes "c"
list.unshift("z"); // ["z","a","b"]
list.shift(); // removes "z"splice and slice
splice changes the array (add/remove items). slice copies a piece without changing the original.
Real-life example: splice — edit the original notebook page. slice — photocopy one page.
const nums = [1, 2, 3, 4];
nums.splice(1, 1, 99); // remove 1 item at index 1, insert 99
// nums is now [1, 99, 3, 4]
const part = [1, 2, 3, 4].slice(1, 3); // [2, 3] — original unchangedmap, filter, find
map transforms each item. filter keeps items that pass a test. find returns the first match.
Real-life example: map — repack every item in new wrapping. filter — keep only ripe mangoes. find — first student with roll 42.
const prices = [100, 200, 300];
const withTax = prices.map((p) => p * 1.18);
const big = prices.filter((p) => p >= 200);
const first = prices.find((p) => p > 150); // 200includes and spread (...)
includes checks if a value exists. Spread ... copies or merges arrays.
Real-life example: includes — "Is mango in the fruit basket?" Spread — pour two baskets into one bigger basket.
[1, 2, 3].includes(2); // true
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b]; // [1, 2, 3, 4]