CKTIS / JavaScript
Object destructuring declaration
An object destructuring declaration creates variable bindings from source properties. The pattern lets you rename bindings, set defaults, and collect the remaining properties.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const { property, key: local = fallback, [computedKey]: selected, nested: { inner } = {}, ...rest } = source;
let { property: mutable } = source;
var { property: variable } = source;An Object destructuring declaration such as const { property } = source; uses braces for a binding pattern, not an object literal. In an ordinary declaration, the source expression is a required initializer. const and let are block-scoped; const prevents rebinding, not mutation of an object. Inside a function, var is function-scoped, not block-scoped.
{ key: local } reads key and declares local, not key. { [computedKey]: selected } computes the key, and a nested pattern reads properties one level deeper. A default expression is evaluated only when the property read returns undefined, for example when the property is missing. It does not replace null, false, or 0. Destructuring null or undefined throws TypeError, including in a nested pattern.
An explicitly selected property can be inherited. ...rest shallowly copies only the remaining own enumerable properties into a new object, including Symbol keys. In a declaration it must come last, bind to an identifier, and have no trailing comma. Destructuring does not validate input; a property read can invoke a getter.
({ property } = source); assigns to an existing variable instead of declaring one. At the start of a statement, parentheses keep the opening { from being parsed as a block. ECMAScript 2024 specifies this syntax; check support in your target runtime.
Examples
{
const key = "theme";
const source = { name: "Ada", theme: null, active: false };
const {
name: displayName,
[key]: theme = "light",
settings: { density = "compact" } = {},
...rest
} = source;
console.log(JSON.stringify([displayName, theme, density, rest]));
}Result
["Ada",null,"compact",{"active":false}]`name` is bound as `displayName`, and `theme` stays `null`. Missing `settings` triggers the `{}` default, then `density` defaults to `"compact"`. Only `active: false` remains in `rest`.
Related lessons
- JavaScript · Lesson 1 · Advanced · Version: 4
- JavaScript · Lesson 8 · Advanced · Version: 4
- JavaScript · Lesson 11 · Advanced · Version: 4
Sources
- ECMAScript 2024 Language Specification — Let and Const Declarations
- ECMAScript 2024 Language Specification — Variable Statement
- ECMAScript 2024 Language Specification — Destructuring Binding Patterns
- ECMAScript 2024 Language Specification — CopyDataProperties
- ECMAScript 2024 Language Specification — Destructuring Assignment
- MDN — Destructuring