180

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
  • 572,313
  • 128
  • 898
  • 1,281
Gajus
  • 62,714
  • 68
  • 259
  • 405
  • 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

344

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
  • 72,859
  • 23
  • 167
  • 174
CodingIntrigue
  • 71,301
  • 29
  • 165
  • 172
  • 31
    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