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

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

Insert well-formed JSON into an HTML element

I'm facing a challenge while trying to dynamically embed a valid JSON array into HTML. The issue arises when the text contains special characters like quotes, apostrophes, or others that require escaping. Let me illustrate the problem with an example ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Exploring Zustand through Laravel validation errorsUnderstanding Zustand can be

I'm currently working on incorporating Zustand into my NextJS application. I have set up a Laravel endpoint for user login functionality. When there are validation errors, the endpoint sends back JSON in the following format: { "message" ...

Learn how to dynamically bind Font Awesome icons in Vue 3 with this easy tutorial

My v-for loop is functioning properly, but I'm having trouble getting the icon to display. How can I correctly bind it? It's worth noting that I have imported and returned the icon, and I am using font awesome in my project. Here are my imports ...

The animation function occasionally halts unexpectedly at a varying position

I am facing an issue with an animation function that I have created to animate a list of images. The function takes in parameters such as frames per second, the stopping point, and the list element containing all the images. However, the animation stops un ...

Step-by-step guide to implementing a sticky header while scrolling

How can I implement a fixed header on scroll, like the one seen on this website: www.avauntmagazine.com Here is the HTML for my header: <div class="bloc bgc-wild-blue-yonder l-bloc " id="bloc-1"> <div class="container bloc-sm"> &l ...

The final condition of the ternary operator fails to render if the specified condition is satisfied

Having trouble identifying the issue with this ternary statement. The last element (blurredscreen) is not appearing when authStatus !== "authenticated". return ( <> <div key={"key-" + id}> {isO ...

Modifying Props in Reactjs: Ways to update data passed from parent component to child component

Currently, I am working on a project where I have multiple components on a page and pass data between them using props. The issue arises when I update the data in the parent component but the child component still uses the old data. Let me illustrate with ...

Utilize React-markdown to interpret subscript text in markdown format

I tried to create subscript text in an .md file using the following syntax: x_i x~i~ Unfortunately, react-markdown did not interpret this as subscript. After some research, I discovered the package remark-sub-super and implemented it with the plugin ...

"Encountered a Parsing Error: function keyword was an unexpected token in an Async Function using a more recent version of Node

In the process of working on a side project, I am utilizing node and firebase technologies. While I have successfully created regular functions and cloud functions, I encountered an issue when attempting to create an async function like so: async function ...

What is the best way to dismiss the additional modal popup?

Here is an example that I need help with: http://jsfiddle.net/zidski/Mz9QU/1/ When clicking on Link2 followed by Link1, I would like the Link2 box to close automatically. Is there anyone who can assist me with this issue? ...

Insert item at the end of the box and move all elements upwards

Hello! I'm experimenting with creating something using javascript's createElement method. My goal is to achieve an effect similar to this image: https://i.stack.imgur.com/itKUK.gif Currently, my code is functional, but the animation goes from to ...

The keyup event fails to trigger for the search input in datatables when ajax is being used

When loading a page with a jQuery datatable via AJAX, I am aiming to implement custom filtering when the user starts typing in the default filter provided by datatables. The custom logic needs to be applied when the keyup event is triggered. Since AJAX is ...

Issues with Angular.js controller functionality

I am currently in the process of learning Angular and have been following the Intro to Angular videos provided on the official Angular website. However, I seem to be encountering an issue with my code that I can't quite figure out. The error message I ...

Leveraging React's State Values and Props

Can you help me with a React component challenge? I have two components that I need to work with: <select> <mytable> I want to build a new component called <myInterface>. The state of <myInterface>, let's call it S, needs to ...

Retrieving JSON data value without a key using AngularJS

I am struggling to retrieve a data value from a JSON array in Angular that does not have a key value. While I have come across examples of extracting values with keys, I haven't been able to crack this particular piece. The JSON returned from the API ...

The progress indicator for AJAX file uploads is malfunctioning; the addEventListener('progress') method is not functioning as intended

For some reason, the event progress listener isn't firing in AJAX when using Chrome web browser. However, when simply using the form submit function to the form action, the file uploads as expected. Even though the file is uploading behind the scenes ...

JavaScript and Angular are used to activate form validation

Update: If I want to fill out the AngularJS Forms using the following code snippet: document.getElementById("username").value = "ZSAdmin" document.getElementById("password").value = "SuperSecure101" How can I trigger the AngularJS Form validation befo ...

Developing a feature to organize content by categories and implement a functionality to load more data efficiently using NodeJS routes

I am looking to develop a system that limits the number of displayed posts and includes a "load more" button to retrieve additional posts from where the limit was previously reached. Additionally, I want to implement the functionality to change the orderin ...