5

I create a Object like below,

var s = {
  `1234`:`string`
}

But, It will throw the below Error,

Uncaught SyntaxError: Unexpected template string

How Can I create Such Elements?

3
  • Object declaration in javascript is done using single or double quotes and not backquotes var s = { "1234": "string" } Commented Sep 26, 2018 at 9:09
  • replace ` with ' single quote Commented Sep 26, 2018 at 9:09
  • Further answers can be found here Commented Feb 13, 2019 at 13:34

2 Answers 2

9

You could use computed property names with brackets, because the template literal returns a string, which works like a variable.

var object = { [`1234`]:`string` };

console.log(object);

Sign up to request clarification or add additional context in comments.

2 Comments

With that we can also avoid the backquote in 1234. Simply [1234]
i think it's more how to use a template litral as key (with computed values), not just taking a constant as key. but i might be wrong ...
1

You should be using quotes instead of backticks, try this:

 var s  = { '123': 'string'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.