🟒 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