These examples show how to read object properties and iterable values into bindings, use defaults and aliases, handle nested data, collect rest values, and assign to existing targets. Each example includes a question, complete code, expected output, and an explanation.
How can two named properties be read into local bindings?
const user = {
name: "Asha",
role: "editor"
};
const { name, role } = user;
console.log(name);
console.log(role);Asha
editor
The object pattern selects properties by their keys. The pattern creates local bindings with the same names and leaves user unchanged.
How can displayName be stored in a local variable called label?
const account = {
displayName: "Mina Dev",
id: 42
};
const { displayName: label, id: accountId } = account;
console.log(label);
console.log(accountId);Mina Dev
42
The property name comes before the colon and the local binding comes after it. This does not rename either property on account.
Can a pattern select some object properties and leave the rest alone?
const product = {
name: "Notebook",
price: 8,
stock: 14
};
const { name, price } = product;
console.log(name);
console.log(price);
console.log(product.stock);Notebook
8
14
Unselected properties do not need bindings. They remain on the original object.
How can a default language be used when a property is absent?
const settings = {
theme: "dark"
};
const { theme, language = "en" } = settings;
console.log(theme);
console.log(language);dark
en
language is missing, so its value is undefined and the default is used.
Which values trigger a destructuring default?
const first = {};
const second = { value: undefined };
const third = { value: null };
const { value: firstValue = "fallback" } = first;
const { value: secondValue = "fallback" } = second;
const { value: thirdValue = "fallback" } = third;
console.log(firstValue);
console.log(secondValue);
console.log(thirdValue);fallback
fallback
null
A missing property and a property containing undefined both trigger the default. Null is a value and is preserved.
Do defaults replace zero, false, or an empty string?
const input = {
retries: 0,
enabled: false,
label: ""
};
const {
retries = 3,
enabled = true,
label = "Untitled"
} = input;
console.log(retries);
console.log(enabled);
console.log(JSON.stringify(label));0
false
""
Defaults apply only to undefined. They do not use a truthiness check.
When is a function used as a default called?
let calls = 0;
function defaultName() {
calls += 1;
return "Guest";
}
const firstUser = { name: "Asha" };
const secondUser = {};
const { name: firstName = defaultName() } = firstUser;
const { name: secondName = defaultName() } = secondUser;
console.log(firstName);
console.log(secondName);
console.log(calls);Asha
Guest
1
The first property has a value, so its default expression is not evaluated. The second property is missing, so the function runs once.
How can city and country be read from a nested address?
const user = {
name: "Mina",
address: {
city: "Pune",
country: "India"
}
};
const {
address: { city, country }
} = user;
console.log(city);
console.log(country);Pune
India
The nested pattern reads the address property and then its city and country properties. It does not create an address binding.
How can both the address object and its city be available?
const user = {
address: {
city: "Pune"
}
};
const {
address,
address: { city }
} = user;
console.log(address.city);
console.log(city);Pune
Pune
The first address entry creates a binding for the whole nested object. The nested pattern separately creates city.
How can a missing address object be handled during nested destructuring?
const user = {};
const {
address: { city = "Unknown" } = {}
} = user;
console.log(city);Unknown
The default empty object is used because address is undefined. The city default then applies because that property is also undefined. This pattern still needs separate handling if address can be null.
How can a variable choose which object property to read?
const field = "email";
const user = {
email: "mina@example.test",
role: "editor"
};
const { [field]: value } = user;
console.log(value);mina@example.test
The brackets evaluate field to select the property key. The colon assigns the selected value to the local variable value.
How can id be separated from the rest of the user's own fields?
const user = {
id: 7,
name: "Mina",
role: "editor",
active: true
};
const { id, ...profile } = user;
console.log(id);
console.log(Object.keys(profile).join(", "));
console.log(profile.role);7
name, role, active
editor
The property id is selected first and excluded from profile. The rest binding receives a new shallow object containing the remaining own enumerable properties.
Does object rest copy a remaining enumerable symbol property?
const internal = Symbol("internal");
const source = {
name: "Asha",
[internal]: 42
};
const { name, ...rest } = source;
console.log(name);
console.log(Reflect.ownKeys(rest).length);
console.log(rest[internal]);Asha
1
42
Object rest includes remaining own enumerable symbol keys as well as string keys.
Which properties remain after destructuring this object?
const prototype = {
inherited: "from prototype"
};
const source = Object.create(prototype);
source.name = "Dev";
Object.defineProperty(source, "hidden", {
value: "not enumerable",
enumerable: false
});
const { name, ...rest } = source;
console.log(rest.inherited);
console.log(rest.hidden);
console.log(Object.keys(rest).length);undefined
undefined
0
Object rest collects remaining own enumerable properties. inherited belongs to the prototype, and hidden is non-enumerable, so neither is copied.
Can ordinary object destructuring read a property from the prototype?
const prototype = {
role: "admin"
};
const user = Object.create(prototype);
user.name = "Asha";
const { role, ...rest } = user;
console.log(role);
console.log(rest.name);
console.log(Object.hasOwn(rest, "role"));admin
Asha
false
The role binding uses ordinary property access and can find an inherited value. Object rest only collects own enumerable properties, so role is not copied into rest.
What happens when the selected object property is a getter?
let reads = 0;
const source = {
get value() {
reads += 1;
return "read";
}
};
const { value } = source;
console.log(value);
console.log(reads);read
1
Destructuring reads the property, which invokes its getter once.
How can the first two colors be assigned to variables?
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first);
console.log(second);red
green
An array pattern consumes iterable values in sequence. It does not remove them from the source array.
How can the second position be skipped?
const coordinates = [12, 30, 48];
const [x, , z] = coordinates;
console.log(x);
console.log(z);12
48
The empty slot in the pattern is an elision. It consumes one value without creating a binding.
How do missing and null values behave with array defaults?
const values = [undefined, null];
const [first = "fallback", second = "fallback", third = "fallback"] = values;
console.log(first);
console.log(second);
console.log(third);fallback
null
fallback
The first value is undefined, the second is null, and the third value is missing. Defaults apply to the first and third values only.
How can the first two scores be separated from all remaining scores?
const scores = [91, 84, 77, 68];
const [best, second, ...remaining] = scores;
console.log(best);
console.log(second);
console.log(remaining.join(", "));91
84
77, 68
The rest element gathers all remaining iterable values into a new array and must be last in the pattern.
How can coordinates from two points be assigned to four variables?
const points = [
[3, 5],
[8, 13]
];
const [[firstX, firstY], [secondX, secondY]] = points;
console.log(firstX, firstY);
console.log(secondX, secondY);3 5
8 13
Each nested pattern consumes values from one inner array.
What values does a string provide to an array pattern?
const [first, second] = "Hi";
console.log(first);
console.log(second);H
i
Strings are iterable, so their iterator provides values to an array pattern.
Does string iteration split this emoji into two separate values?
const [letter, emoji] = "A😀";
console.log(letter);
console.log(emoji);
console.log(emoji.length);A
😀
2
The string iterator yields the emoji as one code point value. That value has a UTF-16 length of two code units.
Can a Set provide values to an array pattern?
const [first, second] = new Set(["red", "blue", "green"]);
console.log(first);
console.log(second);red
blue
A Set is iterable. Destructuring consumes its values in iteration order.
What happens to the generator after two values are destructured?
function* createValues() {
yield "first";
yield "second";
yield "third";
}
const iterator = createValues();
const [first, second] = iterator;
console.log(first);
console.log(second);
console.log(iterator.next().value);first
second
third
Destructuring consumes the first two values from the iterator. The iterator remains positioned at the third value.
What does an array pattern receive from an unassigned array slot?
const values = ["first", , "third"];
const [first, second = "fallback", third] = values;
console.log(first);
console.log(second);
console.log(third);first
fallback
third
The array iterator yields undefined for the empty slot. Since the value is undefined, the default is used.
How can values from an array be assigned to variables declared earlier?
let x;
let y;
[x, y] = [10, 20];
console.log(x);
console.log(y);10
20
This is a destructuring assignment, not a declaration. The targets already exist.
How can properties be assigned to existing variables without a declaration?
let name;
let role;
({ name, role } = {
name: "Asha",
role: "editor"
});
console.log(name);
console.log(role);Asha
editor
The parentheses make the braces parse as an assignment pattern rather than a block statement.
How can object destructuring assignment update existing properties?
const user = {
name: "",
role: ""
};
({ name: user.name, role: user.role } = {
name: "Mina",
role: "author"
});
console.log(user.name);
console.log(user.role);Mina
author
The left side names existing assignment targets. No local name or property is declared by this assignment pattern.
How can two variables exchange values without a temporary variable?
let first = "left";
let second = "right";
[first, second] = [second, first];
console.log(first);
console.log(second);right
left
The right-hand array is evaluated using the original values before assignment updates either variable.
How can a function accept named options and default a missing level?
function createMessage({ text, level = "info" }) {
return "[" + level + "] " + text;
}
console.log(createMessage({ text: "Saved" }));
console.log(createMessage({ text: "Check input", level: "warning" }));[info] Saved
[warning] Check input
The parameter pattern selects named options. The default applies when level is missing or undefined.
How can a function work when its options argument is omitted?
function createLabel({ text = "Untitled", level = "info" } = {}) {
return "[" + level + "] " + text;
}
console.log(createLabel());
console.log(createLabel({ text: "Ready" }));[info] Untitled
[info] Ready
The outer default supplies an empty object for an omitted argument. The inner defaults fill in missing properties.
How can a null profile be treated as an empty object?
const user = {
profile: null
};
const profile = user.profile ?? {};
const { name = "Guest" } = profile;
console.log(name);Guest
The nullish coalescing expression handles both null and undefined before the object pattern reads name.
How can a function accept a coordinate pair?
function describePoint([x, y]) {
return "x=" + x + ", y=" + y;
}
console.log(describePoint([4, 9]));x=4, y=9
The parameter pattern consumes the iterable argument by position. This is a good fit when each position has a fixed, obvious meaning.
How can the two values from a returned array be named at the call site?
function getRange() {
return [4, 9];
}
const [minimum, maximum] = getRange();
console.log(minimum);
console.log(maximum);4
9
The function returns an array, and the caller names its positions with a pattern.
Does selecting array values remove them from the original array?
const values = ["one", "two"];
const [first] = values;
console.log(first);
console.log(values.join(", "));one
one, two
Destructuring reads values. It does not shift or remove array elements.
Does object rest make a deep copy of nested objects?
const source = {
id: 1,
profile: {
name: "Asha"
}
};
const { id, ...copy } = source;
copy.profile.name = "Mina";
console.log(source.profile.name);
console.log(copy.profile.name);
console.log(source === copy);Mina
Mina
false
copy is a new outer object, but its nested profile value is the same object reference used by source.
Can an object pattern read a string's length?
const { length } = "hello";
console.log(length);5
A non-null primitive can be used by an object pattern through its boxed property access. Null and undefined are not destructurable this way.
- Read a property into a differently named local binding.
- Add defaults and compare missing, undefined, null, false, zero, and an empty string.
- Destructure a nested object and provide a default for each potentially missing level.
- Use a computed property name in an object pattern.
- Separate one property from an object with rest and inspect the remaining keys.
- Destructure an array while skipping a value and collecting the remainder.
- Consume a Set or generator with an array pattern.
- Swap two existing variables.
- Use object and array patterns in function parameters.
- Explain why a nested object rest result is shallow.
| Previous chapter | Chapter lesson | Chapter Q&A | Next chapter |
|---|---|---|---|
| 54 - Computed properties, shorthand, and method definitions | Open lesson | Open Q&A | 56 - Spread syntax and rest properties |