I am getting NaN as the output from my function, but I am unsure of the reason behind

For pracitce, I have created this code to calculate the total amount spent on gas and food using arrays. However, I am encountering an issue where it is returning NaN.

const gas = [20, 40, 100];
const food = [10, 40, 50];

function total(gas, food) {
  let gasTotal = 0;
  let foodTotal = 0;

  for (i = 0; i < gas.length; i++) {
    gasTotal += gas[i];
  }
  for (i = 0; i < food.length; i++) {
    foodTotal += food[i];
  }
  const paidtotal = gasTotal + foodTotal;
  console.log(paidtotal);
}

total(gas, food);

Answer №1

Attempting to add up values using undefined.

let waterBill = 0;
let electricityBill = 0;

Setting initial values as numbers should resolve the issue.

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

What is the best way to display a resolved promise object in string format on a button, as an example?

I've searched through many similar questions, but none of them seem to address my specific issue in a simple way. Currently, the behavior of my promise is shown in the image below: https://i.sstatic.net/9GETz.png When looking at lines 62 and 63 in ...

The request in Node.js was terminated

While using express and body-parser to transfer a large amount of data from one server to another, I encountered the following exception after some time: { "message": "request aborted", "code": "ECONNABORTED", "expected": 99010, "length": ...

What is the best way to divide my HTML page in half?

My goal is to display two maps side by side, one on the right and the other on the left. However, when I try to implement this, one map appears on top of the other. I believe that CSS positioning can help me achieve the desired layout, but as a beginner in ...

What is the solution for fixing the "Invalid Element Type" error?

Hey there! I'm currently working on creating a Twitter clone using React, but I've run into an error that's giving me some trouble. The error message reads: "Element type is invalid: expected a string (for built-in components) or a class/fu ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Who is the father of Bootstrap Popover?

I'm currently facing an issue with getting a popover to be placed within a specific element. As of now, the popover is being inserted directly into the <body>, but I require it to be relative to other elements. I have been unable to locate a met ...

Tips for applying various CSS properties to a single element using styled-components

Is there a way to style similar elements differently using different CSS properties in styled components? For example: <div></div> <div></div> With the knowledge I have, I can do: export const StyledDiv = styled.div` color: red; ` ...

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

JavaScript utilizes regex patterns to modify the value located between the characters within an input's name attribute

Can anyone assist me in creating a unique regex pattern to extract specific characters from the attribute values of HTML inputs? I'm dynamically cloning select elements and input text with button clicks, so I need to maintain the attribute name synta ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Variation in functionality of onclick in javascript

Can you identify the distinction between the two primary lines of JavaScript in this example? HTML: <html> <body> <form> <input type="button" value="one" id="one" /> <input type="button" v ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

Is it recommended for the main, module, and browser properties in package.json to reference the minified version or the source

When developing a JavaScript library, it is important to consider the structure in which it will be published. This typically includes various bundles such as CJS, ESM, and UMD, each with their own source, minified, and map files. my-package\ dist& ...

"Encountering a problem with jQuery AJAX - receiving an error message despite the status code being

Attempting to make a jQuery Ajax request using the following code: $.ajax({ url: '<MY_URL>', type: 'POST', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(data), dataType: 'a ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

Wheelnav.js implementing a dynamic bouncing animation

I'm currently in the process of working on a pie menu with wheelnav.js and everything is going smoothly so far. However, I can't seem to find any information in the wheelnav.js documentation on how to eliminate the bouncing effect when a menu cho ...

Running time assessment for JavaScript executions

My current focus is on the execution time of JavaScript programs. Upon running them with nodejs/v8, I have noticed that the time command in the shell produces inconsistent results for execution times. Is there a method to sandbox the execution of these pr ...

Is there a way for my HTML file to connect with my CSS and JavaScript files stored in an Amazon S3 Bucket?

My current project involves hosting an HTML file as a website on AWS S3 in order to circumvent the CORS Policy. However, when I uploaded all my files into a new bucket, the HTML file was able to open but without accessing the accompanying CSS and JavaScrip ...

What is the best way to implement asynchronous guarding for users?

Seeking assistance with implementing async route guard. I have a service that handles user authentication: @Injectable() export class GlobalVarsService { private isAgreeOk = new BehaviorSubject(false); constructor() { }; getAgreeState(): Obser ...