Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on.

Can someone explain the distinction between these two code snippets:

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`);
}

Your insight is greatly appreciated. Thank you!

Answer №1

The primary difference lies in pushing an object into an array versus pushing individual items into an array simultaneously.

let arr = [];
arr.push({key1: value1, key2: value2}); // [{key1: value1, key2: value2}]
arr.push(1, 2); // [1, 2]

Answer №2

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 ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Potential issue of excessive memory usage in node.js when running an Express server with PM2

Currently, I am focusing on a specific aspect of a suite of services designed to work in conjunction with an app/platform. The particular area that requires assistance is related to a vanilla express server used to provide our client app (a react app). We ...

Manipulating object information within a nested for loop

I have a variable called jobs in my scope, which is an array containing objects for each department along with their respective data. [ “Accounting”: { “foo” : “foo”, “bar” : "bar" }, “Delivery”: { ...

Looping through a JSON object in Highcharts to populate data series

I'm brand new to Java Script and I'm on a mission to loop through my JSON object and populate the Highcharts data series. You can take a look at my static demonstration of what I'm trying to achieve on JS Fiddle. Check out JsFiddle here Any ...

Verify user identities using just their passwords

For my express app, I'm tasked with creating an authentication system that uses a 4-digit pin as the password. The code is set up to save and hash the pin along with other user information when adding a new user. Since this is for an in-house server h ...

Include web browsing history

In my ASP.Net/VB project, I am facing an issue with floating DIVs. Whenever users try to close the floating DIV by clicking on the back button in their browser, it creates a confusing experience. My solution is to add a "#" entry to the browser history wh ...

Click to remove the accordion div

My query is regarding an accordion feature that I have implemented. <div id="accordion" class="accord"> <h2> <a href="#">Item1</a></h2> <div> Content1 </div> <h2 > &l ...

Guide to Generating Downloadable Links for JPG Images Stored in MongoDB Using Node.js

I have successfully uploaded an image to MongoDB as a Buffer. Now, I need to figure out how to display this image in my React Native app using a URL, for example: http://localhost:8080/fullImg.jpeg How can I achieve this? Below is the MongoDB Schema I am ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

Differences between Vue.js onMounted and watching refsVue.js offers

When it comes to calling a function that requires an HTMLElement as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting ...

The asterisk path is not processed by the Node command

Within my Test/Automation folder, I have multiple test cases such as a.js, b.js, c.js, and more. Currently, I am utilizing WebdriverJs Selenium to run these tests. To execute all the tests within the folder, I use the following command: node Test/**/*.js ...

Error message: Unable to iterate through a non-iterable object in React reducer

I find myself in a unique predicament and could use some assistance. userData : { isValidCheckup: true, accounts: { userAccount: [ { accountType: 'checkings', includeInCheckup: false }, { accountType: 'check ...

merging JavaScript objects with complex conditions

I am attempting to combine data from two http requests into a single object based on specific conditions. Take a look at the following objects: vehicles: [ { vId: 1, color: 'green', passengers: [ { name: 'Joe', ag ...

Guide to creating a versatile navigation bar using Bootstrap and HTML

I am looking to create a navigation menu that can be easily reused across multiple pages on my bootstrap/html website. Instead of duplicating code, I want to implement a solution for creating a reusable navigation menu in bootstrap/html. How can this be ...

"Creating a new element caused the inline-block display to malfunction

Can someone explain why the createElement function is not maintaining inline-block whitespace between elements? Example problem First rectangle shows normal html string concatenation: var htmlString = '<div class='inline-block'...>&l ...

What is the best way to establish and concentrate on a fresh component in AngularJS?

I am working on a form that has a dynamic number of inputs, which is controlled by AngularJS. <body ng-app="mainApp" ng-controller="CreatePollController" ng-init="init(3)"> <form id="createPollForm"> <input class="create-input" ...

Designing a layout with one box on top and two beneath it, covering the entire page, can be achieved by following these steps

I am currently working on a project where I want to divide the screen into three sections. One section will cover half of the screen to display an image slider, and the remaining half will have two sections which is already done. However, now I need to add ...

I am encountering an issue where the $scope.modal is returning as undefined when attempting to open an Ionic template modal. What

I am currently developing an Ionic application for the iPad. Within one of my templates, I have implemented a treeview with items. My goal is to open other templates modally when users click on these items. However, I encountered an error stating that $sco ...

Combining session values with current array structure for PHP API request

Currently, I am working with an API that requires each request to resend all previous values. To achieve this, I am storing the previous values in a PHP session and then JSON encoding them for use in a Curl request. Everything is functioning correctly exce ...

Angular JS element cannot be located

My Angular object is not being passed when I write a new function, and I'm unsure why. The object, named person, is directly bound in the HTML and returns 2 items from the cardsCollection array. The function I'm attempting to create is called cl ...

Having trouble with the CSS positioning of divs created with JavaScript: it's not behaving as anticipated

Let me start by saying I have always struggled with CSS positioning. It seems like I am missing something simple here... So, I have a JS script that generates divs within a parent container called #container which is set to absolute position. Here is the ...