4

var { foo: bar } = { foo: 123 }; works.

{ foo: bar } = { foo: 123 }; does not.

How to make latter work, when bar is global variable, but destructuring happens inside function?

DoctorDestructo
  • 4,166
  • 25
  • 43
toriningen
  • 7,196
  • 3
  • 46
  • 68

1 Answers1

4

As stated in the "Syntax Gotcha" section in the understandinges6 book, you will need to wrap it using parentheses because otherwise it will generate a syntax error. The opening curly brace is normally the beginning of a block, and blocks cannot be part of an assignment expression.

This worked for me:

var bar;
({ foo: bar } = { foo: 123 });
console.log(bar); // 123

I've also tried:

var bar;
({ foo: bar }) = { foo: 123 };
console.log(bar); // ReferenceError: Invalid left-hand side in assignment at eval

But the latter isn't working for me in es6lint, though the book says it is supposed to work.

mati
  • 5,218
  • 3
  • 32
  • 49