Chapter 8 Cheatsheet: Arrays
This cheatsheet summarizes the mechanics of JavaScript Arrays covered in Chapter 8.
Basics
Arrays are zero-indexed, dynamic collections that can hold mixed data types. The .length property tracks the total count of elements.
const items = ["a", "b", "c"];
items.push("d"); // Appends to the end
console.log(items.length); // 4
const Arrays
const prevents variable reassignment, but it does not prevent array mutation.
const arr = [1];
arr.push(2); // Valid
arr = [3]; // TypeError!
for...of Iteration
The cleanest way to loop over the actual values inside an array without needing an index counter.
const foods = ["pizza", "burger"];
for (const food of foods) {
console.log(food);
}
Core Array Methods
.slice(start, end)
Extracts a shallow copy of a portion of an array. Accepts negative indexes to count from the back.
const arr = [1, 2, 3, 4];
arr.slice(1, 3); // Returns [2, 3]
.includes(value)
Returns a boolean checking if the exact value exists inside the array (or substring inside a string).
["apple", "pear"].includes("apple"); // true
Spread and Destructuring
Spread (...)
Expands elements into a new array. Great for merging.
const arrA = [1, 2];
const arrB = [...arrA, 3, 4]; // [1, 2, 3, 4]
Destructuring Unpacks array elements into distinct variables.
const coordinates = [10, 20, 30, 40];
const [x, y, ...rest] = coordinates;
// x is 10, y is 20, rest is [30, 40]