Chapter 6: The Array Adventures
Arrays are like organized lists in JavaScript Land, and they come with an arsenal of powerful methods.
Creating and Accessing Arrays
// Different ways to create arrays let fruits = ["apple", "banana", "cherry"]; let numbers = new Array(1, 2, 3, 4, 5); let mixed = ["text", 42, true, null, { name: "object" }]; // Array length and access console.log(fruits.length); // 3 console.log(fruits[0]); // "apple" console.log(fruits[-1]); // undefined (no negative indexing) console.log(fruits[fruits.length - 1]); // "cherry" (last element) // Sparse arrays - arrays with holes let sparse = new Array(3); // [empty × 3] sparse[1] = "middle"; // [empty, "middle", empty]
The Mutating Methods - The Array Transformers
let heroes = ["Batman", "Superman"]; // Adding elements heroes.push("Wonder Woman"); // Add to end → ["Batman", "Superman", "Wonder Woman"] heroes.unshift("Aquaman"); // Add to beginning → ["Aquaman", "Batman", "Superman", "Wonder Woman"] // Removing elements let lastHero = heroes.pop(); // Remove from end → "Wonder Woman" let firstHero = heroes.shift(); // Remove from beginning → "Aquaman" // splice - the Swiss Army knife let villains = ["Joker", "Lex Luthor", "Penguin", "Riddler"]; let removed = villains.splice(1, 2); // Remove 2 elements starting at index 1 console.log(villains); // ["Joker", "Riddler"] console.log(removed); // ["Lex Luthor", "Penguin"] // splice can also add elements villains.splice(1, 0, "Catwoman", "Two-Face"); // Insert at index 1 console.log(villains); // ["Joker", "Catwoman", "Two-Face", "Riddler"]
The Non-Mutating Methods - The Array Philosophers
let numbers = [1, 2, 3, 4, 5]; // map - transform each element let doubled = numbers.map(n => n * 2); console.log(doubled); // [2, 4, 6, 8, 10] // filter - select elements that pass a test let evens = numbers.filter(n => n % 2 === 0); console.log(evens); // [2, 4] // reduce - accumulate values into a single result let sum = numbers.reduce((acc, current) => acc + current, 0); console.log(sum); // 15 // More complex reduce example let words = ["Hello", "beautiful", "world"]; let sentence = words.reduce((acc, word, index) => { return acc + word + (index < words.length - 1 ? " " : "!"); }, ""); console.log(sentence); // "Hello beautiful world!" // find - get first element that matches let found = numbers.find(n => n > 3); console.log(found); // 4 // findIndex - get index of first match let foundIndex = numbers.findIndex(n => n > 3); console.log(foundIndex); // 3 // some - test if any element passes let hasEven = numbers.some(n => n % 2 === 0); console.log(hasEven); // true // every - test if all elements pass let allPositive = numbers.every(n => n > 0); console.log(allPositive); // true // includes - check if value exists console.log(numbers.includes(3)); // true console.log(numbers.includes(10)); // false
Array Destructuring - The Unpacking Magician
let colors = ["red", "green", "blue", "yellow"]; // Basic destructuring let [first, second] = colors; console.log(first); // "red" console.log(second); // "green" // Skip elements let [primary, , tertiary] = colors; console.log(primary); // "red" console.log(tertiary); // "blue" // Rest in destructuring let [main, ...others] = colors; console.log(main); // "red" console.log(others); // ["green", "blue", "yellow"] // Default values let [a, b, c, d, e = "purple"] = colors; console.log(e); // "yellow" (from array) let [x, y, z, w, v = "purple"] = ["red", "green"]; console.log(v); // "purple" (default value)
Advanced Array Techniques
Chaining Methods - The Power Combo
let products = [ { name: "Laptop", price: 1200, category: "electronics" }, { name: "Shirt", price: 30, category: "clothing" }, { name: "Phone", price: 800, category: "electronics" }, { name: "Jeans", price: 50, category: "clothing" } ]; // Chain methods for complex operations let electronicsSummary = products .filter(p => p.category === "electronics") .map(p => ({ ...p, discountedPrice: p.price * 0.9 })) .reduce((acc, p) => ({ total: acc.total + p.discountedPrice, items: acc.items + 1 }), { total: 0, items: 0 }); console.log(electronicsSummary); // { total: 1800, items: 2 }
Sorting Arrays - The Order Bringer
// Numbers need special handling let scores = [100, 40, 300, 10, 25]; scores.sort(); // ["10", "100", "25", "300", "40"] - Lexicographic! // Correct numeric sort scores.sort((a, b) => a - b); // [10, 25, 40, 100, 300] // Sorting objects let students = [ { name: "Alice", grade: 85 }, { name: "Bob", grade: 92 }, { name: "Charlie", grade: 78 } ]; // Sort by grade (ascending) students.sort((a, b) => a.grade - b.grade); // Sort by name (alphabetical) students.sort((a, b) => a.name.localeCompare(b.name));
Array.from and Array.of - The Array Creators
// Array.from - convert array-like objects to arrays let nodeList = document.querySelectorAll('div'); // NodeList let divArray = Array.from(nodeList); // With mapping function let squares = Array.from([1, 2, 3, 4], x => x * x); console.log(squares); // [1, 4, 9, 16] // Create range of numbers let range = Array.from({ length: 5 }, (_, i) => i + 1); console.log(range); // [1, 2, 3, 4, 5] // Array.of - create array from arguments let nums = Array.of(7); // [7] let mixed = Array.of(1, 2, "3", true); // [1, 2, "3", true]
Common Array Pitfalls and Interview Tricks
// The empty slots confusion let arr = [1, , 3]; // [1, empty, 3] arr.forEach(x => console.log(x)); // 1, 3 (skips empty) arr.map(x => x * 2); // [2, empty, 6] // Array comparison gotcha console.log([1, 2] === [1, 2]); // false (different references) console.log([] == []); // false // Modifying array during iteration let nums = [1, 2, 3, 4, 5]; nums.forEach((num, index) => { if (num % 2 === 0) { nums.splice(index, 1); // Dangerous! Shifts indices } }); console.log(nums); // [1, 3, 5] - might not be what you expected // Proper way - iterate backwards or use filter nums = [1, 2, 3, 4, 5]; for (let i = nums.length - 1; i >= 0; i--) { if (nums[i] % 2 === 0) { nums.splice(i, 1); } }
Performance Tips
// Pre-allocate array size when possible let bigArray = new Array(10000); // More efficient than pushing 10000 times // Use for loop for best performance on large arrays let sum = 0; for (let i = 0; i < bigArray.length; i++) { sum += bigArray[i]; } // Cache array length in loops for (let i = 0, len = bigArray.length; i < len; i++) { // Process bigArray[i] } // Use typed arrays for numeric operations let float32 = new Float32Array([1.1, 2.2, 3.3]); let int16 = new Int16Array([100, 200, 300]);
Next Chapter: Chapter 7: The Object Kingdom Chronicles
Previous Chapter: Chapter 5: The Function Chronicles
Table of Contents: JavaScript Guide
