The cart total variable in Vuejs is coming back as NaN

I'm currently in the process of creating a cart system using vuejs and I've encountered an issue where my total variable is displaying NaN instead of calculating the total price of all products.

Below is the function responsible for calculating the total

total: function(){
    var totalPrice = 0;
    for (var item in this.products){
        totalPrice += item.price;
    }
    return totalPrice;
}

Next, here's how I have it set up in my template for display

Total Price: ${{total}}

Answer №1

When using a <strong>for in</strong> loop, keep in mind that it is meant for looping through object properties, not arrays. To learn more about this, visit <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="nofollow noreferrer">this link</a>.</p>

<p>If you try to loop through an array using <strong>for in</strong>, you will get the index of the product instead of the product itself. This means that when you execute <code>tot += product.price;
, you are essentially adding 0 (the initial value of tot) and undefined, resulting in NaN.

To properly loop through arrays, consider using the .forEach method like so:

total: function(){
  let tot = 0;
  this.products.forEach(product => tot += product.price)
  return tot;
}

Alternatively, you can utilize the reduce method instead of forEach():

total: function(){
  return this.products.reduce((tot, product) => tot += product.price, 0)
}

Answer №2

If you want to tackle the issue yourself, why not try debugging it by following this code snippet:

  for ( var product in this.products){
    console.log(product);
    tot += product.price;
}

Upon running this snippet, you will realize that product is actually an enumerable property of this.products. In case this.products is an Array, the output will be 0, 1, 2, and so on. For a better understanding of how for..in works, check out the link provided.

Therefore, if you are determined to use for..in, it's recommended to make the following adjustment:

tot += this.products[product].price;

Alternatively, you can opt for a more efficient solution using reduce to sum up the values:

tot: function (){
    var tot = 0;
    tot = this.products.reduce((pre, next) => {
        return pre += next.price;
    }, tot);
    return tot;
}

Answer №3

In the event that the previous solutions are ineffective, consider modifying the return statement to read as follows:

return total || 0

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

The second click does not impact the props received by the child component

I created a basic app with a link to the code. The child component receives props like this: props: ['isActive'], and then it changes its value to display a modal window: data: function() { return { isActive: this.isActive // value from pr ...

Tips for selecting a pagination page number in Python with Selenium

I've been struggling to figure out how to interact with the page numbers of a pagination class for a while now. Despite trying various methods, I can only manage to highlight the container of the number without being able to actually click on it. Bel ...

Adjust the background color of children based on the parent's mouseover event

Seeking a solution to fill three bars with varying percentages: <div class="bars" style="width:0%; background-color: red;"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </ ...

What is the best way to connect my products on an ecommerce site with hundreds of images?

Despite thoroughly searching the internet, I have been unable to find a solution to my dilemma. I am creating a platform that showcases a lengthy list of products on the website. Additionally, I have a database of pictures stored locally that need to be ...

In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value. This serves as my question navigation: /** * * @param {int} question * @returns {QuizPart} ...

Creating a single object from the union of two arrays with JavaScript

I'm looking for a way to merge two arrays into a single object named "data" but haven't discovered an efficient method yet. Here are the arrays: var X = [ 4, 5, 6 ]; var Y = [ d, e, f ]; Merge them into an object: var data = { Y: [ d, e, f ], ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

Navigating through the properties of an object within an array using Angular

In my AngularJs project, I am utilizing the ng-repeat option to display the questionText property within each object in an array. [{ "_id": "57fa2df95010362edb8ce504", "__v": 0, "answers": [], "options": [], "questionText": "what is yo ...

Traversing through intricate weather data in JSON with AngularJS

I've been diving into learning angularJS and have hit a roadblock when it comes to extracting values from specific objects in a JSON file. Despite searching online for solutions, all I've found are basic examples that don't quite fit my curr ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

Tips for reducing code length in jQuery

Here's an interesting question that I've been pondering. Is there a more efficient way to optimize and condense code like the one below? Could it be achieved using functions or loops instead of having lengthy jQuery code? var panels = ["panel1", ...

Animation effects compatible with iOS devices are professionally crafted using CSS

I just implemented a custom hamburger menu with animation using HTML, CSS, and JavaScript on my website. The animation works perfectly on Android devices but not on iOS. Any suggestions for fixing this issue? I attempted to add the Webkit prefix to each p ...

Struggling with implementing the use of XMLHttpRequest to transfer a blob data from MySQL to JavaScript

I have a blob stored in my local WAMP64/MySQL server that I need to retrieve and pass to an HTML file using XMLHttpRequest. I know I should set responseType="blob", but I'm not sure how to transfer the blob from PHP to JavaScript in my HTML file. Any ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...

Tips for dynamically adjusting the size of a div container according to the user's

I have been working on a unique landing page design featuring a menu made up of custom hexagons. I aim to make these hexagons dynamically adjust to fill the entire screen based on the user's resolution, eliminating the need for scrolling. For a previ ...

Operating the VueJS toggle feature on a checkbox

I'm curious about the best way to implement a function toggle using a checkbox in VueJS. <input v-model="discount" type="checkbox" name="discount"> My goal is to update a string in my view when the discount checkbox is checked, displaying the ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Customizing content based on Route - Utilizing Node.js/React

I am currently working on setting up routes for different pages of store profiles in my Node app. I have been doing some research online and have come to understand how to adjust the parameters, but I am struggling with figuring out how to dynamically chan ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...