How do array and object destructuring decide which value goes into which variable?
const [a, b] takes items 0 and 1; const { a, b } takes properties a and b, whatever their order in the object.
Destructuring · Exercise 1 of 4
Fifteen multiple-choice questions on JavaScript destructuring: array and object patterns, skipping, defaults, renaming, rest, nested patterns, parameters, assignment syntax, iterables and errors. Pick an option to check your answer instantly.
How do array and object destructuring decide which value goes into which variable?
const [a, b] takes items 0 and 1; const { a, b } takes properties a and b, whatever their order in the object.
For const { theme = "light" } = settings;, which value of settings.theme makes theme equal to "light"?
Destructuring defaults – like default parameters – apply only for undefined. null, "", 0 and false are kept.
What does const { name: fullName } = user; do?
In an object pattern the left side is the property to read and the right side is the variable to create.
Which pattern reads obj.size into a variable s, defaulting to 10?
The order is property : variable = default.
Which destructuring pattern is valid?
There can be only one rest element and it must be the last element of the pattern.
What happens with const { id } = null;?
null and undefined have no properties, so destructuring them throws. (value ?? {}) avoids it.
Variables a and b already exist. Which statement assigns obj.a and obj.b to them?
Without parentheses the leading { starts a block, which is a SyntaxError. let would redeclare the variables, and an array pattern needs an iterable.
Which pattern takes only the third item of arr?
Each empty comma skips one position. (An object pattern with an index key, const { 2: third } = arr, also works.)
After const { password, ...safe } = user;, what is safe?
Object rest creates a new shallow copy minus the destructured keys; user is unchanged. Nested objects are still shared.
In const { city = fetchCity() } = data;, when is fetchCity called?
Defaults are evaluated lazily, only when needed. A falsy but defined value such as "" does not trigger them.
Timed online tests with instant scores and explanations.