0

I am trying to destructure object and assign it to new variable at the same time:

let {x} = a = {x: 'cool'};
console.log(a, x);

which outputs:

//Object { x: "cool" } cool - in Firefox
//ReferenceError: a is not defined - in Chrome, babel-node

Why is there difference and what is the correct behavior?

UPDATE:

This is maybe more generic use case. While this works in all environments:

var a = b = {x: 'cool'};

this statement is not working in chrome/babel-node:

var {x} = a = {x: 'cool'}; //SyntaxError: Unexpected token {

There is also different error message when using var instead of let.

madox2
  • 49,493
  • 17
  • 99
  • 99
  • The problem is, as the error message says, `a` is not defined. `let a = b = c` does **not** define `b`. Firefox may be doing some default declaration for you, eg in the console. –  Jan 18 '16 at 14:04
  • @torazaburo that's correct. But `let a = b = c` is possible in firefox (not in chrome) – madox2 Jan 18 '16 at 14:06
  • For me, in babel-node `var a = b = {x: 'cool'};` gives a ReferenceError, as of course it should. The difference in error messages between `let` and `var` could be related to support of `let` in different environments. `var {x} = a = {x: 'cool'};` in babel-node does not give the error you report; it gives me the same ReferenceError, again as it should. –  Jan 18 '16 at 14:19
  • @torazaburo so chrome behavior is correct? – madox2 Jan 18 '16 at 14:20
  • I'm confused as to what you say is working or not working and generating what error in what environment. I suggest adding a little table to your question. Meanwhile, why don't you just write correct code instead of worrying about different environments reporting errors in different ways? –  Jan 18 '16 at 14:22
  • @torazaburo I am just curious how it works and what is possible. – madox2 Jan 18 '16 at 14:34

1 Answers1

2

In your code, a is not defined. let a = b = c does not define b. You need to say

let a = {x: 1}, {x} = a;

Firefox doesn't support let, so I'm wondering how your example worked there at all. See https://kangax.github.io/compat-table/es6/.