How do default values and renaming work in object and array destructuring?
In objects, {name: n = 'x'} reads property name into variable n with a default used only when the value is undefined. In arrays, position matters: [a, , c = 9]. Defaults ignore null.
Explain it simply
Destructuring is unpacking a tiffin box: instead of opening it and taking items one at a time, you declare which compartment goes to which name in one line.
For objects, names must match property names. To use a different variable name, write { oldName: newName }. To give a fallback, add = value.
For arrays, order matters, and you can skip a position with an empty comma.
Defaults only kick in for undefined, not for null, 0 or "". And you can swap two variables without a temp: [x, y] = [y, x].
Example
const student = { name: "Asha", marks: null };
const { name: studentName, age = 18, city = "Pune", marks = 50 } = student;
console.log(studentName); // Output: Asha
console.log(age); // Output: 18
console.log(city); // Output: Pune
console.log(marks); // Output: null
const [first, , third = 9] = [1, 2];
console.log(first); // Output: 1
console.log(third); // Output: 9
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // Output: 2 1What to say in the interview
"Object destructuring matches by property name, with name: alias to rename and = default for missing values. Array destructuring matches by position. Defaults apply only when the value is undefined, so null stays null."
Common mistakes
- Expecting a default to replace null or 0.
- Forgetting the semicolon before a line starting with [ or ( and getting a confusing error.