Lesson 4 of 12 · 9 min · Core language
Arrays and objects: methods, destructuring and spread
What you will learn
- Create and change arrays, and the methods you use daily
map,filter,reduce,find,some,every,sortand the immutabletoSorted- Objects: properties, shorthand, computed keys,
Object.keys,entries,fromEntries - Destructuring, spread and rest
Map,Set, grouping and copying data without mutating the original
In simple words
Almost every web page is made of lists of things (orders, courses, messages) and records with properties (a user with a name and email). Arrays hold the lists and objects hold the records. JavaScript gives you a rich set of tools for transforming them in one line, such as "take all paid orders and add up their amounts", and shortcuts for unpacking and copying them.
Words to know
- Array: an ordered list of values, indexed from 0.
- Object: a collection of named properties (key and value pairs).
- Destructuring: unpacking values from arrays or objects into variables.
- Spread: expanding an array or object into individual items, written
....
Arrays
const skills = ["sql", "excel", "python"];
skills[0]; // "sql"
skills.at(-1); // "python" (negative index counts from the end)
skills.length; // 3
skills.push("java"); // add at the end (mutates)
skills.pop(); // remove from the end (mutates)
skills.unshift("stats"); // add at the start (mutates)
skills.shift(); // remove from the start (mutates)
skills.includes("sql"); // true
skills.indexOf("excel"); // 1
skills.slice(1, 3); // ["excel", "python"] (copy of part; original unchanged)
skills.splice(1, 1); // remove 1 item at index 1 (mutates!)
skills.join(", "); // "sql, python"
Array.isArray(skills); // true
Know which methods mutate the array (push, pop, shift, unshift, splice, sort, reverse) and which return a new one (slice, map, filter, concat, flat, and the newer toSorted, toReversed, toSpliced, with). In React and most modern code, do not mutate state; create new arrays.
The transforming methods
const orders = [
{ id: 101, customer: "Asha", status: "paid", amount: 1200 },
{ id: 102, customer: "Asha", status: "paid", amount: 800 },
{ id: 103, customer: "Ravi", status: "refunded", amount: 1500 },
{ id: 104, customer: "Meena", status: "paid", amount: 600 },
];
orders.map(o => o.amount); // [1200, 800, 1500, 600] transform each
orders.filter(o => o.status === "paid"); // 3 orders keep some
orders.find(o => o.id === 103); // the order object or undefined first match
orders.findIndex(o => o.id === 103); // 2
orders.some(o => o.amount > 1000); // true any?
orders.every(o => o.amount > 500); // true all?
const paidTotal = orders
.filter(o => o.status === "paid")
.reduce((sum, o) => sum + o.amount, 0); // 2600 (the 0 is the starting value)
orders.flatMap(o => [o.id, o.customer]); // map then flatten one level
[[1, 2], [3, [4]]].flat(); // [1, 2, 3, [4]] (flat(Infinity) flattens fully)
forEach runs a function for side effects and returns nothing; use map when you want a new array, and a for...of loop when you need break, continue or await.
for (const order of orders) { if (order.amount > 1000) break; }
for (const [index, order] of orders.entries()) { /* index and value */ }
Sorting
sort() mutates and, by default, compares items as strings: [10, 9, 100].sort() gives [10, 100, 9]. Always give a comparison function:
const amounts = [1200, 800, 1500, 600];
[...amounts].sort((a, b) => a - b); // [600, 800, 1200, 1500] copy first, then sort
amounts.toSorted((a, b) => b - a); // [1500, 1200, 800, 600] non-mutating (ES2023)
orders.toSorted((a, b) => a.customer.localeCompare(b.customer) || b.amount - a.amount);
Use localeCompare for text (correct for accents and other scripts). The sort is stable.
Objects
const name = "Asha";
const user = {
name, // shorthand for name: name
email: "asha@example.com",
"home-city": "Hyderabad", // quote keys that are not valid identifiers
[`skill_${1}`]: "SQL", // computed key
greet() { return `Hi ${this.name}`; }, // method shorthand
};
user.name; // dot access
user["home-city"]; // bracket access (dynamic keys, odd names)
user.phone; // undefined (no error)
user.address?.city; // undefined: ?. stops safely on a missing address
delete user.email;
"name" in user; // true
Object.hasOwn(user, "name"); // true
Object.keys(user); // keys
Object.values(user); // values
Object.entries(user); // [[key, value], ...]
Object.fromEntries([["a", 1], ["b", 2]]); // { a: 1, b: 2 }
Object.freeze(user); // shallow immutability (writes are ignored or throw in strict mode)
Transform an object: Object.fromEntries(Object.entries(prices).map(([item, p]) => [item, p * 1.18])).
Destructuring, spread and rest
const [first, second, ...others] = ["sql", "excel", "python", "java"]; // first = "sql", others = ["python", "java"]
let x = 1, y = 2;
[x, y] = [y, x]; // swap two variables: x = 2, y = 1
const { name, email, phone = "n/a", address: { city } = {} } = user; // defaults and nesting
const { id, ...rest } = order; // rest: everything except id
function show({ name, age = 18 }) { /* destructure parameters */ }
function sum(...numbers) { return numbers.reduce((s, n) => s + n, 0); } // rest parameter
const merged = { ...defaults, ...overrides }; // later wins
const updated = { ...user, city: "Pune" }; // copy with a change (immutable update)
const withNew = [...skills, "java"]; // copy with an addition
Math.max(...amounts); // spread into arguments
Spread makes shallow copies: nested objects are shared. Use structuredClone(obj) for a deep copy.
Immutable update patterns
const state = { user: { name: "Asha", skills: ["sql"] }, loading: false };
const next = {
...state,
user: { ...state.user, skills: [...state.user.skills, "python"] }, // copy every level you change
};
const removed = skills.filter(s => s !== "excel"); // delete by filtering
const replaced = orders.map(o => o.id === 102 ? { ...o, status: "refunded" } : o); // update one
Map and Set
Objects have string keys and some inherited properties; Map keeps any type of key in insertion order, with a size and fast frequent updates; Set stores unique values.
const stock = new Map([["pen", 100], ["book", 40]]);
stock.set("bag", 5);
stock.get("pen"); // 100
stock.has("cap"); // false
stock.size; // 3
for (const [item, qty] of stock) { /* iterate */ }
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]
const a = new Set([1, 2, 3]), b = new Set([2, 3, 4]);
a.intersection(b); // Set {2, 3} (new Set methods in current browsers and Node 22+)
a.union(b); a.difference(b);
Grouping and counting
const byStatus = Object.groupBy(orders, o => o.status);
// { paid: [3 orders], refunded: [1 order] } (ES2024; also Map.groupBy)
const counts = orders.reduce((acc, o) => {
acc[o.status] = (acc[o.status] ?? 0) + 1;
return acc;
}, {}); // { paid: 3, refunded: 1 }
JSON
const text = JSON.stringify(orders[0]); // '{"id":101,...}'
const back = JSON.parse(text); // object again (wrap in try/catch: bad JSON throws)
JSON.stringify(data, null, 2); // pretty print
JSON drops functions and undefined and turns dates into strings; NaN becomes null.
Common mistakes
- Mutating arrays and objects that other code (or React state) depends on.
- Using
sort()without a comparison function on numbers. - Using
mapfor side effects orforEachwhen you need a result. - Believing spread makes deep copies.
- Using
for...inon arrays (iterates keys, including inherited ones; usefor...of). - Using objects as dictionaries with user-supplied keys (
__proto__risks; useMap). - Forgetting that
reducewithout an initial value fails on an empty array.
Try it yourself
- With the
ordersarray: get paid orders, their total, the customer names without duplicates, and the largest order. - Group orders by customer with
Object.groupByand withreduce. - Rename a key in an object and change a nested value without mutating the original (spread).
- Sort orders by customer name, then amount descending, without modifying the original array.
- Count word frequencies in a sentence using a
Map.
Check yourself
What is the difference between map and forEach?
map returns a new array of the results of the callback; forEach returns nothing and is used for side effects.
Why does [10, 9, 100].sort() give [10, 100, 9]?
Without a comparison function, sort converts items to strings and compares them alphabetically; use (a, b) => a - b.
What does the spread operator copy?
The top level only (a shallow copy); nested objects are shared. Use structuredClone for deep copies.
What does const { id, ...rest } = order do?
It extracts id into a variable and collects the remaining properties into a new object rest.
Interview questions
How do you remove duplicates from an array?
[...new Set(array)] for primitives; for objects, use a Map keyed by an id or filter on the first index of each key.
Which array methods mutate the original?
push, pop, shift, unshift, splice, sort, reverse and fill; non-mutating alternatives include slice, map, filter, toSorted, toReversed and toSpliced.
How do you deep clone an object?
structuredClone(obj) (supports most built-in types, but not functions); JSON.parse(JSON.stringify(obj)) works only for plain JSON data and loses dates, undefined and functions.
Summary
- Arrays: know the mutating and non-mutating methods; use
map,filter,reduce,find,some,every,toSorted. - Objects: shorthand, computed keys,
Object.entries/fromEntries, optional chaining andhasOwn. - Destructuring, spread and rest unpack and copy data; spread is shallow,
structuredCloneis deep. - Use
MapandSetwhere objects and arrays are awkward; update state immutably.
Going deeper
- MDN: Indexed collections (arrays): the array guide.
- MDN: Array reference: every method.
- MDN: Destructuring assignment: patterns and defaults.
- MDN: Keyed collections (Map and Set): when to use them.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.