Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can’t back ticks be used in JavaScript objects [duplicate]

Tags:

javascript

Why are back ticks for object properties invalid syntax? For example, this is valid:

const test = {
  "test1": "test2"
}

So why can’t it have back ticks instead?

const test = {
  `test1`: "test2"
}
//throws unexpected token error

It would be really helpful if back ticks could be used like this, but we can’t. Is there a simple alternative, or maybe this works in some browsers?

like image 863
MrMythical Avatar asked Jul 18 '26 21:07

MrMythical


1 Answers

You need to put it into brackets like this because it's evaluated at runtime.

const test = {
  [`test1`]: "test2"
}

As @Amadan pointed out in the comment, you can use any expression as a property key by putting it into brackets.

like image 129
snak Avatar answered Jul 20 '26 11:07

snak



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!