0
const BUTTON_TYPE_CLASSES = {
  base : 'base',
  inverted : 'inverted'
}

const getButton = (buttonType) =>
({
  [BUTTON_TYPE_CLASSES.base] : BaseComponent,
  [BUTTON_TYPE_CLASSES.inverted] : InvertedComponent,
}[buttonType]);

I understand what this code blocks mean. But I don't know what works brackets in object of function getButton.

Why don't use just BUTTON_TYPE_CLASSES.base : BaseComponent... ? Why use [BUTTON_TYPE_CLASSES.base] : BaseComponent... ?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • It's [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names), it allows you to use an expression that then evalutes to a key on the object. Without it (the `[]`), it would be a syntax error in your case. – Nick Parsons Jun 26 '22 at 06:29
  • That means to use the value of the variable `BUTTON_TYPE_CLASSES.base` as the property name, instead of a fixed string. – Barmar Jun 26 '22 at 06:29
  • @NickParsons Thanks. Name is same with Key? – gogadoro92 Jun 26 '22 at 06:37
  • @gogadoro92 not too sure what you're asking, but in `{foo: 123}`, you would call `foo` a _key_ or a _property_. Computed property names allow you to create `foo` dynamically, eg: `{["f" + "oo"]: 123}` evaluates to the object of `{foo: 123}`. Doing just `{"f" + "oo": 123}` without the `[]` wouldn't work. So the value between the `[]` is evaluated and used as the key on the newly created object. – Nick Parsons Jun 26 '22 at 06:41
  • @NickParsons Thanks for your answer. I understood if I would like to use expression as key of object, I have to use [ ] around expression which used as key of object. Thank you – gogadoro92 Jun 26 '22 at 16:51

0 Answers0