Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
push as object, or as separated items

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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]
about 4 years ago · Juan Pablo Isaza Report

0

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 ]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!