Skip to main content
CodeOath
← All posts

JavaScript60 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Part 9 of 16 · ~1 min

Destructuring

Destructuring is shorthand for unpacking an array or object into separate named variables in one step, rather than reaching in and grabbing each field individually — and the syntax turns up in more corners of the language than it first appears to.

const [first, second] = candidates;      // first = Priya, second = Diego
const [, , third] = candidates;          // skip two with empty commas — third = Amara

const [topScorer, ...everyoneElse] = candidates.toSorted((a, b) => b.score - a.score);
// topScorer = Amara, everyoneElse = the other four, still sorted

const { name, score } = candidates[0];              // name = "Priya Shah", score = 82
const { name: candidateName } = candidates[0];       // rename while destructuring — candidateName = "Priya Shah"
const { location = "remote" } = candidates[0];       // candidates[0] has no `location` field — location = "remote"

function summarize({ name, score, location = "remote" } = {}) { // default for the WHOLE object too
  console.log(`${name}: ${score} (${location})`);
}
summarize(candidates[0]); // "Priya Shah: 82 (remote)"
summarize();               // works because of `= {}` — without it, destructuring undefined throws

Notice where that = {} sits — on the whole parameter, not tucked in next to role. That's what lets summarize() survive being called with zero arguments. Remove it, and calling the function with nothing forces JavaScript to destructure undefined itself, which fails right away — the individual field defaults inside never get a turn to run at all.

It's also legal directly in a for...of loop's variable slot, which is the whole reason looping over what Object.entries() hands back reads so cleanly:

for (const [category, rating] of Object.entries(feedback)) {
  console.log(category, rating); // "communication" 8, then "systemDesign" 7, then "coding" 9
}