3

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?

MrMythical
  • 8,908
  • 2
  • 17
  • 45

2 Answers2

11

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.

snak
  • 6,483
  • 3
  • 23
  • 33
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names – Amadan Oct 11 '21 at 03:46
0

You can write like this:

const key = `test1`
const test = { [key]: 'test2' }
AntiLun
  • 53
  • 1
  • 4