EasyModern JS📖 Theory Question

Explain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.

💡

Hint

Extract values into variables with concise syntax — works in params, assignments, loops

Full Answer

// ── Array destructuring (position-based) ─────
const [a, b, c] = [1, 2, 3];
const [first, , third] = [1, 2, 3];    // skip index 1
const [x, ...rest] = [1, 2, 3, 4];     // x=1, rest=[2,3,4]
const [p = 10, q = 20] = [1];          // p=1, q=20 (default)

// ── Object destructuring (name-based) ────────
const { name, age } = { name: 'Alice', age: 25 };
const { name: userName } = { name: 'Alice' };  // rename to userName
const { city = 'NYC' } = {};                    // default if undefined

// ── Nested ────────────────────────────────────
const { address: { city: town } } = { address: { city: 'Paris' } };
// town = 'Paris'

// ── In function parameters ────────────────────
function greet({ name, age = 18, role = 'user' }) {
  return `${name} (age:${age}, ${role})`;
}

// ── Swap variables ────────────────────────────
let m = 1, n = 2;
[m, n] = [n, m]; // m=2, n=1

// ── In loops ─────────────────────────────────
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value);
}
💡 Destructuring doesn't mutate the original — it creates new bindings. Combine default params + destructuring for clean, self-documenting function signatures.

More Modern JS Questions

MediumWhat are generators and when would you use them?→EasyWhat is optional chaining (?.) and nullish coalescing (??)?→EasyWhat are tagged template literals and what are they used for?→EasyWhat are Symbols and what are their main use cases?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint