12

I am not very experienced with javascript and have a question relating to curly braces used around a function parameter, since its not a JSON structure.

I am learning nuclear js, and I found some code as example, but I don't understand it well - why is "product" is in braces?:

addToCart(product) {
    reactor.dispatch(ADD_TO_CART, { product })
}

Thx

Rich
  • 970
  • 2
  • 16
  • 42
Marcin Kurpiel
  • 175
  • 1
  • 8

2 Answers2

20

This is an ES2015 (also called ES6) shorthand to create objects.

{ product } is equivalent to { product: product }.

Basically, you end up with an object with a property called "product" that has the value of the product variable.

const prop = "prop value";
const obj = { prop, anotherProp: "something else" }
console.log("obj: ", obj);

Have a look at the MDN documentation and here if you need a more detailed explanation.

It is a relatively new syntax so old browsers (e.g. IE) are likely to raise a syntax error, however it starts to be quite well supported amongst modern browsers. Have a look here for the ES2015 compatibility table.

zwessels
  • 617
  • 1
  • 10
  • 25
Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
2

This is ES6 shorthand syntax for defining object having same key as the variable name.

{product} is same as { product: product }.

Property Shorthand

MDN Docs

Tushar
  • 85,780
  • 21
  • 159
  • 179