1

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.

Lazar Nikolic
  • 4,261
  • 1
  • 22
  • 46
Lucien
  • 123
  • 8
  • 1
    Simply because property keys must be delimited by `'` or `"` - a string literal not a template expression. – Bergi Sep 21 '18 at 14:13
  • 1
    I think this may answer at least partially: https://stackoverflow.com/questions/33194138/template-string-as-object-property-name/35902149#35902149 – ESN Sep 21 '18 at 14:13
  • Thank you, that post answers my question. – Lucien Sep 21 '18 at 14:16

1 Answers1

2

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614