Arrays and Objects
~340 words ยท 2 min read
Arrays โ ordered lists
const fruits = ["apple", "banana", "cherry"];
// Common methods
fruits.push("date"); // add to end
fruits.pop(); // remove from end
fruits.map(f => f.toUpperCase()); // new array: ["APPLE", ...]
fruits.filter(f => f.startsWith("a")); // ["apple"]
fruits.find(f => f === "banana"); // "banana" or undefined
Objects โ key-value pairs
const user = {
name: "Alice",
age: 30,
isAdmin: true,
};
Destructuring
Extract values concisely:
// Object destructuring
const { name, age } = user;
// Array destructuring
const [first, second] = fruits;
// Rename during destructuring
const { name: fullName } = user;
Spread and rest
The ... operator does two things depending on context:
// Spread โ unpack into a new array/object
const copy = [...fruits];
const merged = { ...user, email: "a@b.com" };
// Rest โ collect remaining args
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
Spread creates shallow copies โ nested objects still share references.
Immutable updates
Avoid mutating data directly โ create new copies instead:
// Bad โ mutates original
user.age = 31;
// Good โ creates new object
const updated = { ...user, age: 31 };
This pattern is essential for React and Redux, which rely on detecting changes by reference.