JSJavaScript · Lesson 5 of 14
Arrays & Objects
Arrays and objects are the backbone of JavaScript data. Master these and you've mastered 80% of what you'll actually use.
JavaScript
// Arrays
const numbers = [1, 2, 3, 4, 5];
// Core array methods
numbers.push(6); // add to end
numbers.unshift(0); // add to start
numbers.pop(); // remove from end
numbers.shift(); // remove from start
const sliced = numbers.slice(1, 3); // [2, 3] (non-destructive)
numbers.splice(1, 2); // remove 2 elements at index 1 (mutates)
// Transformation methods (return new arrays)
const doubled = [1,2,3].map(x => x * 2); // [2, 4, 6]
const evens = [1,2,3,4].filter(x => x % 2 === 0); // [2, 4]
const sum = [1,2,3].reduce((acc, x) => acc + x, 0); // 6
const found = [1,2,3,4].find(x => x > 2); // 3
const hasEven = [1,2,3].some(x => x % 2 === 0); // true
const allPos = [1,2,3].every(x => x > 0); // true
// Spread and destructuring
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1,2,3,4,5,6]
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3, 4, 5]JavaScript
// Objects
const person = {
name: "Alice",
age: 30,
greet() { // method shorthand
return `Hi, I'm ${this.name}`;
}
};
console.log(person.name); // Alice
console.log(person["age"]); // 30
console.log(person.greet()); // Hi, I'm Alice
// Object destructuring
const { name, age, city = "Unknown" } = person;
console.log(name, age, city); // Alice 30 Unknown
// Spread for copying/merging
const updated = { ...person, age: 31, email: "alice@example.com" };
// Object methods
console.log(Object.keys(person)); // ["name", "age", "greet"]
console.log(Object.values(person)); // ["Alice", 30, [Function]]
console.log(Object.entries(person)); // [["name","Alice"], ...]
// Optional chaining and nullish coalescing
const config = { server: { port: 3000 } };
const port = config?.server?.port ?? 8080; // 3000
const host = config?.server?.host ?? "localhost"; // "localhost"