Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.
Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.
Array DestructuringValues in arrays are destructured based on their index . The variable can be named anything you want, but the variable name associated with the index is how it is assigned. We can also assign values to variables that are already declared.
The issue stems from the {...}
operators having multiple meanings in JavaScript.
When {
appears at the start of a Statement, it'll always represent a block, which can't be assigned to. If it appears later in the Statement as an Expression, then it'll represent an Object.
The var
helps make this distinction, since it can't be followed by a Statement, as will grouping parenthesis:
( {a, b} = objectReturningFunction() );
From their docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assignment_without_declaration
Notes: 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 is var {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.
If you write Javascript without semicolons, then the 'assignment without declaration' syntax should be preceded with a semicolon for it to work predictably
let a, b
;({a, b} = objectReturningFunction()) // <-- note the preceding ;
Just wanted to highlight this as it caught me out, and hopefully can save others some time figuring out why it doesn't work and/or produces weird results with code formatters like prettier
.
Indeed, it's actually right there in the accepted answer (last line of the quoted docs) but easy to miss, especially without seeing an example!
Here's another way:
let {} = {a, b} = objectReturningFunction()
Pros:
Cons:
!(){...}()
IIFE.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With