Search code examples
javascriptecmascript-6ecmascript-next

Object deconstruction assignment without variable declaration in ES6


Is it possible to have a deconstructing assignment expression in ES6 without the need of declaring variables?

In other words, why is the following code syntactically incorrect?

(I know there are a lot of ways this code could be rewritten.)

'use strict';

let var1 = 'defaultVal1', var2 = 'defaultVal2';
const obj = { group: { var1: 'newVal1', var2: 'newVal2' } }
if (obj) {
  { group: { var1, var2 } } = obj; // No 'let'/'const' keyword, i.e. no redeclaration, but invalid expression
}
console.log(var1);
console.log(var2);


Solution

  • The brackets are interpreted as block statement, but you need an expression. This can be archived by wrapping it with parentheses as an assignment without declaration.

    'use strict';
    
    let var1 = 'defaultVal1', var2 = 'defaultVal2';
    const obj = { group: { var1: 'newVal1', var2: 'newVal2' } }
    if (obj) {
      ({ group: { var1, var2 } } = obj); // No 'let'/'const' keyword, i.e. no redeclaration, but invalid expression
    }
    console.log(var1);
    console.log(var2);