The program keeps encountering the issue of returning undefined while attempting to calculate the sum of elements in an array

I'm having trouble with the code below, it seems to be returning undefined for the sum of the array. Any advice or assistance would be greatly appreciated.

    var myExpenses = [];
            var total;

        function appendExpenses() {
            var expense = document.getElementById('cost').value;
            myExpenses.push(expense);
            console.log(myExpenses);

            function calculateTotalExpense() {
                for (var i = 0; i < myExpenses.length; i++) {
                    total = total + myExpenses[i];
                }
                return total;
            }
            console.log(total);
        }

Answer №1

  1. Ensure variables have meaningful default values.

    let totalAmount = 0;

  2. Explicitly convert data types when necessary.

    let expenseValue = parseFloat(document.getElementById('cost').value)

  3. Always validate the data before using it.

    if (!isNaN(expenseValue)) expensesArray.push(expenseValue)

  4. Remember to call your function.

    function calculateTotalExpenses() {
        const expensesArray = [];
        let totalAmount = 0;
        let expenseValue = parseFloat(document.getElementById('cost').value);
        if (!isNaN(expenseValue)) {
          expensesArray.push(expenseValue);
        }
    
        console.log(expensesArray);
        
        return function () {  
            for (var i = 0; i < expensesArray.length; i++) {
                totalAmount += expensesArray[i];
            }
            return totalAmount;
        }
    }
    
    const totalExpenseValue = calculateTotalExpenses()
    console.log(totalExpenseValue())
    

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

React.js - Error message: onChange is not defined

My application has successfully integrated the last.fm API to fetch related artists. The concept is simple - search for an artist and receive a list of related artists in return. While using 'onClick' works flawlessly as it retrieves the input v ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...

JavaScript tool for implementing sorting features on an HTML table

I am facing an issue with my AJAX-loaded table where I need sorting functionality implemented. Despite searching for various JavaScript plugins, none seem to work efficiently due to slow performance or errors. The structure of my HTML table is unique with ...

Utilizing Javascript to create interactive images in HTML

Is there a way for JavaScript to open the current image in a new WINDOW when an ONCLICK event occurs? <script> function imgWindow() { window.open("image") } </script> HTML <img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" ...

Looking to retrieve the key value or iteration of a specific item within an Angular UI tree?

Here is a snippet of code showcasing how to use angular-ui-tree: <div ui-tree> <ol ui-tree-nodes="" ng-model="list"> <li ng-repeat="item in list" ui-tree-node> <div ui-tree-handle> {{item.title}} </div& ...

Accessing local JSON data through JavaScript

I am looking to access a JSON file locally using JavaScript. The file is named "posts.json" and contains the following information: { "post0": "<empty>", //1 "post1": "<empty>", //2 "post ...

Encountering a build time issue while incorporating Redis into Next.js

Incorporating Redis into my Next.js project has been beneficial overall. However, during the build process (next build), an error arises when it attempts to connect to Redis, resulting in the following message: Collecting page data ..[ioredis] Unhandled e ...

Implementing concurrent operations in React Native using Firebase, combining async/await with Promise.all

import fire from '../config/fire'; const db = fire.firestore(); class InitialDb extends Component { constructor(props) { super(props); this.state = { schools: '', students: '', }; } async compo ...

Issue with vuejs build process not incorporating relative paths into the final output

I'm encountering a problem trying to run my Vue.js app from the dist folder. After searching on this site, I came across a helpful thread titled Vuejs, Difficulties to build with relative path, which suggested the following solution: Create a "vu ...

Avoid triggering the parent modal to close when a child element is clicked in VueJS

In my Vue application, there is a situation where I have a button called "detach button" with a @click function inside an element that is clickable. When clicking on this parent element, it triggers another @click function and toggles a Bootstrap modal eve ...

The .removeAttr('checked') method fails to function as expected

I am currently using CodeIgniter. Check out this example of my code. Please fill the textbox and check the checkbox next to it, then click on the "add" link. You will notice that it does not work as expected..removeAttr('checked') newDiv.find(&a ...

What steps can I take to stop Google Maps from resetting after a geocode search?

As a beginner working with the Google Maps Javascript API v.3, I have written some code to initialize a map, perform an address lookup using the geocoder, re-center the map based on the obtained lat long coordinates, and place a marker. However, I am facin ...

Guide on adjusting shadow intensity with a Directional Light on a BoxGeometry in Three.js

I've been working on adjusting the light and shadow settings for Box Geometry. Specifically, I am using a Directional light with a certain intensity level. However, I've noticed that when I decrease the intensity, the plane appears darker while t ...

Generate a collection of information by gathering metadata from Xray

I've been struggling to populate an array with metadata retrieved using Xray. The issue arises when the function is called by an API endpoint on my server to fetch links from my application. My main challenge seems to be related to promises, as there ...

The jQuery script automatically triggers submission on its own

Does anyone have an idea why the form auto-submits itself? I can't figure out why it's doing that. I'm using query parsley to validate the form in a modal. When a user opens the modal and starts typing in the text area, they must type at l ...

Optimize the performance of filtering large GeoJSON files using Ajax in leaflet for the

I am managing four 2MB geoJson files with four different Layers that need to be loaded. Each layer is loaded using the following code: LayerBoon = L.geoJSON.ajax(URL, {pointToLayer:returnBoonMarker, filter:filtertext}); There is also a button click functi ...

Size of Output from RSA 2048 Encryption Using JSEncrypt

I've been under the impression that the output size of RSA 2048 bit encryption is 256 bytes. However, I keep getting 344 characters as output when using jsencrypt for testing. Can anyone shed some light on why this discrepancy exists? Tool used for o ...

Email Form Application: Utilizing NodeJs and Express - Error: URL Not Found /

I'm encountering a "cannot GET" error whenever I try to run my application on a live server using VS Code. My assumption is that the issue lies within my routing configuration, but I'm struggling to identify the exact problem. Any assistance woul ...