When it comes to this scenario:
cart.push({product, quantity})
it is essentially the same as:
cart.push({ product: product, quantity: quantity})
The concept of using Shorthand property names was first introduced in ES2015/es6.
If a property name matches a variable name (which contains the property value), you can directly assign the variable without repeating the property name while creating the object.
In your situation, you are inserting an object with properties property
and quantity
into an array named cart
.
So upon console logging, you will encounter something like
[{'property': 'bottle', 'quantity': 99 }]
On the other hand:
cart.push(product, quantity);
demonstrates adding two elements whose values come from variables product
and quantity
. When logged on the console, it will appear similar to ['bottle', 99 ]
cart = [];
//cart = [];
const addToCart = function(product, quantity){
cart.push({product, quantity});
console.log(cart);
}
const addToCart2 = function(product, quantity){
cart.push(product, quantity);
console.log(cart);
}
addToCart("product 1", 100); // [ { "product": "product 1", "quantity": 100 }]
//addToCart2("product 1", 100); // [ "product 1", 100 ]