//
Arrays are ordered collections of values. JavaScript arrays are dynamic (no fixed size), can hold mixed types, and come with dozens of powerful built-in methods.
1const fruits = ["apple", "banana", "cherry"];2const numbers = [1, 2, 3, 4, 5];3const mixed = [1, "two", true, null, { name: "Alice" }];4const empty = [];56// Array constructor (less common)7const zeros = new Array(5).fill(0); // [0, 0, 0, 0, 0]89// Array.from - create from iterables10const chars = Array.from("Hello"); // ["H", "e", "l", "l", "o"]11const range = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
1const fruits = ["apple", "banana", "cherry"];23console.log(fruits[0]); // "apple"4console.log(fruits.at(-1)); // "cherry" (negative indexing)5console.log(fruits.length); // 367// Modify8fruits[1] = "blueberry";9console.log(fruits); // ["apple", "blueberry", "cherry"]
| Method | Action | Returns | Mutates? |
|---|---|---|---|
push() | Add to end | New length | ✅ |
pop() | Remove from end | Removed item | ✅ |
unshift() | Add to beginning | New length | ✅ |
shift() | Remove from beginning | Removed item | ✅ |
splice() | Add/remove at index | Removed items | ✅ |
1const arr = [1, 2, 3];23// End4arr.push(4); // [1, 2, 3, 4]5arr.pop(); // [1, 2, 3] - returns 467// Beginning8arr.unshift(0); // [0, 1, 2, 3]9arr.shift(); // [1, 2, 3] - returns 01011// Splice: splice(start, deleteCount, ...items)12arr.splice(1, 1); // [1, 3] - removed "2"13arr.splice(1, 0, 2, 2.5); // [1, 2, 2.5, 3] - inserted
Immutable Alternatives
Methods like push and splice modify the original array. For immutable patterns, use spread: [...arr, newItem] instead of arr.push(newItem).
1const nums = [10, 20, 30, 20, 40];23console.log(nums.indexOf(20)); // 1 (first occurrence)4console.log(nums.lastIndexOf(20)); // 3 (last occurrence)5console.log(nums.includes(30)); // true67// find - returns first matching element8const users = [9{ name: "Alice", age: 25 },10{ name: "Bob", age: 30 },11{ name: "Charlie", age: 35 },12];1314const bob = users.find(u => u.name === "Bob");15console.log(bob); // { name: "Bob", age: 30 }1617// findIndex - returns index of first match18const bobIndex = users.findIndex(u => u.name === "Bob");19console.log(bobIndex); // 12021// some - at least one matches?22console.log(users.some(u => u.age > 30)); // true2324// every - all match?25console.log(users.every(u => u.age > 20)); // true
1const numbers = [1, 2, 3, 4, 5];23const doubled = numbers.map(n => n * 2);4console.log(doubled); // [2, 4, 6, 8, 10]56const names = ["alice", "bob", "charlie"];7const capitalized = names.map(name =>8name.charAt(0).toUpperCase() + name.slice(1)9);10console.log(capitalized); // ["Alice", "Bob", "Charlie"]
1const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];23const evens = numbers.filter(n => n % 2 === 0);4console.log(evens); // [2, 4, 6, 8, 10]56const products = [7{ name: "Laptop", price: 999 },8{ name: "Mouse", price: 25 },9{ name: "Keyboard", price: 75 },10{ name: "Monitor", price: 450 },11];1213const expensive = products.filter(p => p.price > 100);14console.log(expensive); // [Laptop, Monitor]
1const numbers = [1, 2, 3, 4, 5];23// Sum4const sum = numbers.reduce((acc, n) => acc + n, 0);5console.log(sum); // 1567// Max value8const max = numbers.reduce((a, b) => a > b ? a : b);9console.log(max); // 51011// Group by category12const items = [13{ name: "Apple", category: "fruit" },14{ name: "Carrot", category: "vegetable" },15{ name: "Banana", category: "fruit" },16{ name: "Broccoli", category: "vegetable" },17];1819const grouped = items.reduce((groups, item) => {20const key = item.category;21groups[key] = groups[key] || [];22groups[key].push(item.name);23return groups;24}, {});2526console.log(grouped);27// { fruit: ["Apple", "Banana"], vegetable: ["Carrot", "Broccoli"] }
Chaining Methods
map, filter, and reduce return new values, so you can chain them: arr.filter(...).map(...).reduce(...).
1// sort() mutates and sorts as strings by default!2const nums = [10, 1, 21, 2];3nums.sort();4console.log(nums); // [1, 10, 2, 21] - string sorting!56// Numeric sort7nums.sort((a, b) => a - b); // Ascending: [1, 2, 10, 21]8nums.sort((a, b) => b - a); // Descending: [21, 10, 2, 1]910// Sort objects11const users = [12{ name: "Charlie", age: 35 },13{ name: "Alice", age: 25 },14{ name: "Bob", age: 30 },15];16users.sort((a, b) => a.age - b.age);17// Sorted by age ascending1819// Non-mutating sort with toSorted() (ES2023)20const sorted = [3, 1, 2].toSorted((a, b) => a - b);21// original unchanged, sorted = [1, 2, 3]
sort() Mutates!
sort() modifies the original array. To sort without mutating, use [...arr].sort() or the new toSorted() method.
1// Spread - copy and combine2const a = [1, 2, 3];3const b = [4, 5, 6];4const combined = [...a, ...b]; // [1, 2, 3, 4, 5, 6]56// Copy (shallow)7const copy = [...a];89// Destructuring10const [first, second, ...rest] = [10, 20, 30, 40, 50];11console.log(first); // 1012console.log(second); // 2013console.log(rest); // [30, 40, 50]1415// Skip elements16const [, , third] = [1, 2, 3];17console.log(third); // 31819// Swap variables20let x = 1, y = 2;21[x, y] = [y, x];22console.log(x, y); // 2, 1
1// flat - flatten nested arrays2console.log([1, [2, [3, [4]]]].flat(Infinity)); // [1, 2, 3, 4]34// flatMap - map + flatten5console.log([[1,2],[3,4]].flatMap(x => x)); // [1, 2, 3, 4]67// join - array to string8console.log(["Hello", "World"].join(" ")); // "Hello World"910// concat - combine arrays (non-mutating)11console.log([1, 2].concat([3, 4])); // [1, 2, 3, 4]1213// slice - extract portion (non-mutating)14console.log([1,2,3,4,5].slice(1, 3)); // [2, 3]1516// reverse - reverses in place17// toReversed() - non-mutating reverse (ES2023)
1const students = [2{ name: "Alice", scores: [92, 88, 95, 91] },3{ name: "Bob", scores: [78, 82, 75, 80] },4{ name: "Charlie", scores: [95, 98, 92, 97] },5{ name: "Diana", scores: [65, 70, 72, 68] },6];78const report = students9.map(student => ({10name: student.name,11average: student.scores.reduce((a, b) => a + b, 0) / student.scores.length,12}))13.map(s => ({14...s,15grade: s.average >= 90 ? "A" : s.average >= 80 ? "B" : s.average >= 70 ? "C" : "D",16}))17.sort((a, b) => b.average - a.average);1819console.log(report);20// [21// { name: "Charlie", average: 95.5, grade: "A" },22// { name: "Alice", average: 91.5, grade: "A" },23// { name: "Bob", average: 78.75, grade: "C" },24// { name: "Diana", average: 68.75, grade: "D" },25// ]
Now let's explore objects and destructuring - the other fundamental data structure in JavaScript.