Template String As Object Property Name

trysis picture trysis · Oct 18, 2015 · Viewed 33.2k times · Source

Why does JavaScript not allow a template string as an object property key? For example, when I input:

foo = {`bar`: 'baz'}

into the NodeJS REPL, it throws a SyntaxError with "Unexpected template string" with a long stack trace. Property values are fine, however, which is not as unexpected. Similar errors happen in the browser, for example, Firebug throws a SyntaxError with "invalid property id".

Template strings are allowed in "computed property names". For instance, this compiles perfectly fine in all browsers that support the syntax:

var foo = {
    [`bar` + 1]: `baz`
};

and creates the object {"bar1": "baz"}.

Why are template strings not allowed as literal object keys? Is it for performance reasons? Template strings must be compiled, possibly at runtime (correct me if I'm wrong), which means every time it encounters this object, the interpreter will have to compute the object name. Factoring in things like "cooked" template strings, this seems like it could get slow, although we have had getters and setters since ES5. Firefox does not mention this as an error, which is why I found it unexpected. Will the syntax be allowed sometime in the future?

Answer

Bergi picture Bergi · Mar 9, 2016

Why are template strings not allowed as literal object keys?

Template strings are expressions, not literals1. You can only use string literals (and identifiers) for property names, for everything else - that is not known to be static - you need a computed property name.

Is it for performance reasons?

No, that's unlikely. It's to ease parsing, and makes it easy to distinguish constant (statically known) property names from dynamically computed ones.

And mostly, it's a feature that no one needs. It doesn't simplify or shorten anything, and what you would achieve with it is already possible.

Will the syntax be allowed sometime in the future?

Nope.

1: Even when they're called "template literals", technically they aren't literals. And: templates don't even need to be strings, they can evaluate to anything.