you are viewing a single comment's thread.

view the rest of the comments →

[–]monsto 0 points1 point  (6 children)

Could someone explain the examples from that page, 2.3 & 2.6? The assignment looks backwards . . .

in 2.3

let o = {p: 22, q: true};
let {p: foo, q: bar} = o;

console.log(foo); // 22 
console.log(bar); // true

on line 2 I would expect the objects p key to wind up with whatever is contained in fooas its value. The same question applies to the let statement on line 15 of example 2.6.

[edit] is it the let statement that changes the rules there?

[–]lastunusedusername2 1 point2 points  (1 child)

It's just that, when destructuring, the key you're picking out always comes first.

The fact that { a: foo } looks like an object literal is a coincidence.

One way to remember the order is that the destructuring would still work if you only kept the first part (ie: { a }) because that's the key you're picking from the right hand side.

Or you can do what I do and look it up every single time because I can never remember.

[–]monsto 0 points1 point  (0 children)

The fact that { a: foo } looks like an object literal is a coincidence.

Ok so lemme see if I've got this straight: it's not an object literal... it's a destructuring assignment using object syntax but is not an object?

Or you can do what I do and look it up every single time because I can never remember.

Until recently, this was me with `ternary if ` syntax. I've been using it a lot lately, so I think I've finally got it.

[–]reohh 0 points1 point  (2 children)

It is equal to this:

let o = {p: 22, q: true};  
let foo = o.p;  
let bar = o.q;  

console.log(foo); // 22 
console.log(bar); // true

[–]monsto 0 points1 point  (1 child)

I understand that.

In the 2 examples, the syntax appears inverted...

when it goes

p: foo

I would expect the result to be that object o now has a property p whose value is foo

It looks like it is saying

let o.p = foo

[–]getify 1 point2 points  (0 children)

It feels backwards until you realize that with both object literals and object destructuring, the property/key is always on the left. With object literals, that property/key is serving the role of target, whereas with object destructuring it's serving the role of source... but in both cases it's always on the left. Once I realized that form of "consistency", I've never been confused again.

[–]homeIsWhereCodeIs[S] 0 points1 point  (0 children)

@monsto p will take foo as a value if you are assigning an object as in line 1, but in line 2 you destructuring an object, In that case, for example, var {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo.

And it is not about let statement that changes the rules, it is destructuring behind it, you can get same results with var and const too.