Destructuring assignment – JavaScript | MDN
Posted by jpluimers on 2023/11/29
Since I didn’t know that JavaScript could deconstruct (a superset of Parallel Assignment) [Wayback/Archive] Destructuring assignment – JavaScript | MDN of which I copied the topmost examples (there are far more in the rest of the article):
let a, b, rest; [a, b] = [10, 20]; console.log(a); // 10 console.log(b); // 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] ({ a, b } = { a: 10, b: 20 }); console.log(a); // 10 console.log(b); // 20 // Stage 4(finished) proposal ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}); console.log(a); // 10 console.log(b); // 20 console.log(rest); // {c: 30, d: 40}
Note that the last two examples (about destructuring objects) require extra parenthesis. You do not need them when assigning the variables (vars or lets) or consts at the declaration site:
Note: The parentheses
( ... )around the assignment statement are required when using object literal destructuring assignment without a declaration.
{a, b} = {a: 1, b: 2}is not valid stand-alone syntax, as the{a, b}on the left-hand side is considered a block and not an object literal.However,
({a, b} = {a: 1, b: 2})is valid, as isconst {a, b} = {a: 1, b: 2}Your
( ... )expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.
Related:
- [Wayback/Archive]
var– JavaScript | MDN
The
varstatement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. - [Wayback/Archive] let – JavaScript | MDN
The
letstatement declares a block-scoped local variable, optionally initializing it to a value. - [Wayback/Archive] const – JavaScript | MDN
Constants are block-scoped, much like variables declared using the [Wayback/Archive]
letkeyword. The value of a constant can’t be changed through reassignment (i.e. by using the [Wayback/Archive] assignment operator), and it can’t be redeclared (i.e. through a [Wayback/Archive] variable declaration). However, if a constant is an [Wayback/Archive] object or [Wayback/Archive] array its properties or items can be updated or removed.
Via [Wayback/Archive] javascript decompose – Google Search (as I tend to mix up this – or even deconstruct – with the actual term destructure).
–jeroen






Leave a comment