Object destructuring syntax - ES6

I had been through array destructuring syntax, which is well understood.

What exactly are we doing below, when we say var {p, q} = o;?

Is p and q in var {p, q} different from properties of o i.e., 'p' and 'q'? If yes,

why var {a, b} = o; does not work?

> var o = {p: 42, q: true};
> p
    ReferenceError: p is not defined
> q
    ReferenceError: q is not defined
> o['p']
> o['q']
> var {p, q} = o;
> p
> q
> var {a, b} = o;
> a
> b

*Note: I learnt that, dictionary keys are string literals in javascript.*


    var o = {p: 42, q: true};
     var {p, q} = o;

Here, var {p,q} = o is just a shorthand for var {p:p , q:q} = o

Consider this.

      var o = { key : "value" };
      var { key : local_var } = o ;
      local_var === o["key"] // true

If you omit the local_var, and write var {key} = o; a new variable key will be created with the idenifier "key"., same like doing var key = o["key"]

So in your example that's like doing

      var p =  o["p"] ;  //42
       var q = o["q"];   //true
       var a = o["a"];  // undefined
       var b = o["b"];   //undefined

This may not be exactly true, but should help you understand it.
It's kind of something like Pattern Matching that other languages provide, but it's different.


That's because using your syntax for object destructing, the names used in the LHS expression ({a, b}) are used as keys into the RHS expression (o). Since a and b are not properties of o, that fails (returns undefined).

The relevant section in the spec for this is in Runtime Semantics: DestructingAssignmentEvaluation under AssignmentProperty : IdentifierReference Initializer (2nd from last). AssignmentProperty are your a (and b... separately), and. The StringValue of a is 'a' and that is used as a key to get a value from o (equivalent o['a'] in this case).

It would work if you'd do:

var {p:a, q:b} = o;

which uses AssignmentProperty : PropertyName : AssignmentElement (last entry) which uses a propery name (p) AND an assignment element (a).


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.