Array methods and destructuring
Transform data with map, filter and reduce, and unpack values cleanly.
Instead of loops that build results by hand, modern JavaScript transforms collections with methods that take a function. They return a new array and do not change the original (except sort, which does).
const products = [
{ name: "Pen", price: 2, stock: 10 },
{ name: "Book", price: 12, stock: 0 },
{ name: "Bag", price: 30, stock: 3 },
];
const names = products.map((p) => p.name);
const available = products.filter((p) => p.stock > 0);
const total = products.reduce((sum, p) => sum + p.price * p.stock, 0);
const book = products.find((p) => p.name === "Book");
const anyEmpty = products.some((p) => p.stock === 0);
const allCheap = products.every((p) => p.price < 50);maptransforms each item.filterkeeps some.reducecombines all into one value.findreturns the first match (orundefined).someandeveryreturn booleans.- Chain them:
products.filter(p => p.stock > 0).map(p => p.name).
Destructuring, spread and rest
const { name, price = 0 } = products[0]; // object destructuring with a default
const [first, ...others] = products; // array destructuring and rest
const updated = { ...products[0], price: 3 }; // copy with a change (spread)
const more = [...products, { name: "Cap", price: 8, stock: 5 }];CarefulSpread makes a shallow copy. Nested objects are still shared with the original. For a deep copy use structuredClone(value).
Notesort() changes the array in place and compares as strings by default. Use [...arr].sort((a, b) => a - b) for numbers without mutating the original.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.