2

I noticed somewhere that we could define an object using the following syntax:

const a = {
  ["test"]: 1,
  ["tmp"]: 2,
};

Is it the same as the following one?

const b = {
  "test": 1,
  "tmp": 2,
};

If so, what's the [] for in the first code block?

Searene
  • 25,920
  • 39
  • 129
  • 186

1 Answers1

2

It is an ES6 feature called Computed Property Names
When using it a great benefit is you can also put variables as key name. Like for example a string which includes variables

const a = {
  [`obj${someVariable}`]: 1,
  [`obj${anotherVariable}`]: 2,
};

const someVariable = 4;
const anotherVariable = 3;
const a = {
  [`obj${someVariable}`]: 1,
  [`obj${anotherVariable}`]: 2,
};

console.log(a)

Here are a few examples

Aalexander
  • 4,987
  • 3
  • 11
  • 34