Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't we add object property names using template strings [duplicate]

i want to add or modify an object using property name that is a variable.

i found out that the way to use dynamic property names is using square brackets,

var x ="hi"

a = {
...a,
[x]:"hello"
}

above code works and object a has new property named "hi".

we can add a new property using a string property name like below.

a = {
...a,
"hiwithstring":"hello with string"
}

above code works fine as it is the normal way. even if we don't keep name in string quotes, js engine internally does that for us.

using string interpolation, we can include variables into string like below,

var x ="hiWithInterpolation"
 var propName = `${x}`
//now propName is "hiWithInterpolation".

now my question is why can't we use string interpolation to add dynamic property names like below ?

var x ="hiWithInterpolation"
a = {
...a,
`${x}`:"helloWithINterPolation"
}

above code doesn't work and throws Uncaught SyntaxError: Unexpected template string.

coudl someone explain why last example is failing ?

like image 448
Ayyappa Gollu Avatar asked Nov 30 '25 03:11

Ayyappa Gollu


1 Answers

You need a computed property name.

var x = "hiWithInterpolation";
a = {
    ...a,
    [`${x}`]: "helloWithINterPolation"
};
like image 193
Nina Scholz Avatar answered Dec 03 '25 19:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!