Template String As Object Property Name

Javascriptnode.jsObject LiteralTemplate StringsTemplate Literals

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

> 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.

Solution 2 - Javascript

Object keys are expected to be Strings.

If the expression provided as a key is not a string, the engine will attempt to Coerse it into a string.

Template Strings are not 'coersible', hense, the engine throws an error trying to coerse them (example 1)

Arrays, on the other hand, are naturally coersible to string, therefore can be used as completely legal keys

Moreover, arrays that contain template strings may be used as perfectly legal keys when creating an object, because the engine first evaluates the template expression, then coerses the array into a string (example 2)

see examples:

    /* example 1 */ {`foo`: "bar"}   // Error: template strs aren't coersible

To be able to use a template string as an object key, just wrap it as single element of an array:

    /* example 2 */ {[`foo`]: "bar"} /* OK: {foo: "bar"}, the internal `foo` 
                                           template is first resolved to a native 
                                           "foo" string, resulting in array ["foo"],
                                           which then coersed to the "foo" key.*/
    
    /* example 3 */ const obj = {foo: "bar"}
                        const obj1 = {[obj.foo]: "bar"} // OK: {bar: "bar"} !!

Solution 3 - Javascript

I'm posting this answer to lift @Bergi's very upvoted comment to an answer. If you want to use a dynamic value from a variable as your object key in your object literal, just use a computed property:

const dynamicKey = someCondition ? 'someKeyName' : 'otherKeyName';
const obj = {[dynamicKey]: val};

You could also write that as:

const obj = {[`${dynamicKey}`]: val};

but why bother?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrysisView Question on Stackoverflow
Solution 1 - JavascriptBergiView Answer on Stackoverflow
Solution 2 - JavascriptNati KamusherView Answer on Stackoverflow
Solution 3 - JavascriptdavidethellView Answer on Stackoverflow