1

Using array destructuring I can assign a value to a reference:

const o = {}
;[o['something']] = ['a', 'b', 'c']
console.log(o) // { something: 'a' }

But I cannot do the same with object destructuring. Why?

const o = {}
{ ['1']: o['something'] } = { '1': 'a' } // Syntax Error
Ben Aston
  • 53,718
  • 65
  • 205
  • 331

2 Answers2

5

You can. The issue is just that the { } is interpreted as block here instead of an object literal! For the same reason you can't write { a: 1 }.a.

You can wrap the whole statement in parens to avoid this problem (in the same way as ({ a: 1 }).a makes the previous example work):

const o = {}
;({ ['1']: o['something'] } = { '1': 'a' })
console.log(o) // { something: 'a' }
CherryDT
  • 25,571
  • 5
  • 49
  • 74
1

A variable can be assigned its value with destructuring separate from its declaration using the parentheses ( ... ) around the assignment statement like:

const o = {};
({ ['1']: o['something'] } = { '1': 'a' });

console.log( o )

As mentioned in the docs,

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

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2}

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

Community
  • 1
  • 1
palaѕн
  • 72,112
  • 17
  • 116
  • 136