DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
CABrouwers
CABrouwers

Posted on

Who can explain this deceptively simple destructuring assignment?

Code

var a
[a] = [2]
console.log("a->",a)

var b = {}
[b] = [3]
console.log("b->",b)
Enter fullscreen mode Exit fullscreen mode

Output

a-> 2
b-> [ 3 ]
Enter fullscreen mode Exit fullscreen mode

Why is the second output different? How is the assignment working?

Thanks

Top comments (5)

Collapse
 
stereobooster profile image
stereobooster • Edited on

You miss semicolon

var b = {};
[b] = [3]
console.log("b->",b)
Enter fullscreen mode Exit fullscreen mode

this would work as expected. It is easy to discover, if you use let:

let b = {}
[b] = [3]
console.log("b->",b)
// Uncaught ReferenceError: can't access lexical declaration 'b' before initialization
Enter fullscreen mode Exit fullscreen mode

Original code:

var b = {}
[b] = [3]
Enter fullscreen mode Exit fullscreen mode

which is the same as

var b = {}[b] = [3]
Enter fullscreen mode Exit fullscreen mode

which is the same as

var b = [3]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
cabrouwers profile image
CABrouwers Author • Edited on

Thanks a lot. It seemed absurd to me. All makes sense now!

Collapse
 
myleftshoe profile image
myleftshoe

Wow, nice spot, and worrying for me because I never use semicolons anymore. But I also almost never use var. I guess I've been luck so far.

Collapse
 
fselcukcan profile image
F. Selรงuk Can • Edited on

@stereobooster 's explanation about missing semicolon is correct. In JavaScript in order to terminate a block, {}, you need to type a semicolon, ;.

Unexpected behaviour arises in a number of cases like this. I have never seen your case before.

Another example of this is when you return an object literal which spans multiple lines from a function and do not terminate the return statement after the closing brace of the object literal you return. Interpreter can confuse your object literal with a block since they have same syntax.

Telling that I can say that I have seen that case before :).

My suggestion is to use semicolon after at least object literals. You can choose to use semicolons to terminate only blocks and object literals or even after every line to stay safe.

Collapse
 
jamesthomson profile image
James Thomson

Personally I always use semicolons, I prefer to know exactly where my blocks are terminating. I think it's also that I've been writing JS for so long that I find it unnerving to see no semicolons.

Classic DEV Post:

caching

Web Caching Explained by Buying Milk at the Supermarket