217

The following produces a syntax error:

let source,
    screenings,
    size;

source = {
    screenings: 'a',
    size: 'b'
};

{
    screenings,
    size
} = source;

Expected result:

screenings should be equal to 'a'
size should be equal to 'b'
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Gajus
  • 69,002
  • 70
  • 275
  • 438
  • See my answer [here](https://stackoverflow.com/a/71492680/979621) for a gist of the ways of applying destructuring to existing variables or existing objects. – SNag Mar 16 '22 at 06:36

1 Answers1

414

You need to use assignment separate from declaration syntax:

({
    screenings,
    size
} = source);

Babel REPL Example

From the linked docs:

The ( .. ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration

And obviously you need to use this as you can't redeclare a let variable. If you were using var, you could just redeclare var { screenings, size } = source;

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 40
    As I also posted [in the answer here](https://stackoverflow.com/a/56068605/1082449) this syntax needs to be preceded by a semicolon if you *don't* write JS with semicolons - i.e. `;({ screenings, size } = source)` – davnicwil May 09 '19 at 23:04