I have very simple question.
But what is the difference between:
export const addToCart = function(product, quantity){
cart.push({product, quantity});
console.log(`${quantity} ${product} are added`);
}
and
export const addToCart = function(product, quantity){
cart.push(product, quantity);
console.log(`${quantity} ${product} are added`);
}
Thank you
First is push an object into an array while second is push each item into an array.
var a =[];
a.push({b:1,c:2}) // [{b: 1, c: 2}]
a.push(1,2) // [1,2]
In this case:
cart.push({product, quantity})
is equals to
cart.push({ product: product, quantity: quantity})
This Shorthand property names was introduced in ES2015/es6. When there is a property name that is same as a variable name (a variable that contains your property value), you do not need to mention the property name while initializing the object.
So in your case, you are adding an object with properties property and quantity into a cart array.
So when you console log you will see like [{'property': 'bottle', 'quantity': 99 }]
In this case:
cart.push(product, quantity);
you are normally adding two items whose value is in product and quantity variables. So when you console log you will see something like ['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 ]