Why does object destructuring assignment throw an error when using template strings?

597 Views Asked by At

In JavaScript, it is possible to assign variables through object deconstruction like so:

let a = {b: 2};
let {b} = a;
console.log(b); // 2

Sometimes the property that needs to be accessed isn't a valid variable name, in which case an alternative identifier can be passed:

let a = {'words with spaces': 2};
let {'words with spaces': words_without_spaces} = a;
console.log(words_without_spaces); // 2

This works for both single quote strings and double quote strings. However, an error is thrown when trying to do the exact same thing with a template string:

let a = {'words with spaces': 2};
let {`words with spaces`: words_without_spaces} = a;
     ^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected template string

Why does using a template string here cause an error whereas other strings don't? I understand that the template string could be defined as a variable beforehand and then passed using computed property brackets, but I'm just curious as to what the reason is behind the above code not working.

1

There are 1 best solutions below

0
On BEST ANSWER

The language syntax allows for a property name in an object initializer or a descructuring left-hand-side of an assignment to be a string literal but not a template. That's just the way the grammar is defined.