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
  • 22,811
  • 37
  • 122
  • 172

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,893
  • 3
  • 10
  • 31