Unpack only the values you need
Destructuring binds values from arrays or object properties into local names. It is syntax for extraction, not a deep-copy operation. Object patterns match property names; array patterns match positions.
const student = { name: 'Asha', score: 82 };
const { name, score: marks, city = 'Not provided' } = student;
console.log(name, marks, city); // Asha 82 Not provided
const result = ['passed', 82, 100];
const [status, earned, maximum] = result;
console.log(status, earned / maximum); // passed 0.82score:marks renames the local variable; it does not rename the property on student. A default applies only when the extracted value is undefined, not when it is null, zero or an empty string.
Function parameters
function label({ title, duration = 10 } = {}) {
return String(title ?? 'Untitled') + ' (' + duration + ' min)';
}
console.log(label({ title: 'Loops' })); // Loops (10 min)
console.log(label()); // Untitled (10 min)The outer default handles an omitted/undefined argument. It does not make label(null) safe, because null cannot be destructured as an object. Validate an external payload before unpacking it.
Skip and collect
const [first, , third] = [10, 20, 30];
const { score, ...otherFields } = student;
console.log(first, third); // 10 30
console.log(otherFields); // { name: 'Asha' }Rest collects remaining own enumerable properties into a new object. Nested object references still point to their original objects. Avoid deeply nested patterns when a missing intermediate object would cause an unclear error.
Practice
- Extract a course title and rename its id to courseId.
- Test a default against undefined, null and zero.
- Swap two let bindings with
[left, right] = [right, left]. - Explain why destructuring a nested address does not clone that address.
हिन्दी संकेत: object destructuring नाम देखता है, array destructuring position। Default केवल undefined पर लगता है।