Why is my JavaScript code resulting in an error about a function not being defined?

New to JavaScript and encountering an issue with a function that should loop through an array when a button is clicked. However, I am getting an error message stating:

showWorthSum() function is not defined.

   function addWorth()
    { 


        var table1= document.getElementById("tableNetWorths");

        var rowCount1= table1.rows.length;

        var row1= table1.insertRow(rowCount1);


        var arr= [];


       for(count = 0; count < rowCount1; count++)
       {    
            arr.push(table1.rows[count].cells[1].innerHTML);          
       }


       arr.shift();
       return arr;

    } 

    function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(int count = 0; count < arrCount; count++)
        {    
             //totalWorth= totalWorth+ returnedArr[count]; 

            document.write(returnedArr[count]);
            //debugger;
        }

        //return totalWorth;
    }

Button:

   <button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>

Script tags have been carefully handled in the code above. Below is the full HTML code:

<!DOCTYPE html>
<html>
<head>
<link href="css/basic.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">

<script>
    function alterTable()
    { 

        //Textboxes code

        var tBoxCompany= document.getElementById("txtboxCompany");
        var tBoxAmount= document.getElementById("txtboxAmount");



        //table code

        var table= document.getElementById("tableNetWorths");

        var rowCount= table.rows.length;

        var row= table.insertRow(rowCount);

        var Cell1= row.insertCell(0);
        var Cell2= row.insertCell(1);

        Cell1.innerHTML= tBoxCompany.value;
        Cell2.innerHTML= tBoxAmount.value;

    }    

    function addWorth()
    { 


        var table1= document.getElementById("tableNetWorths");

        var rowCount1= table1.rows.length;

        var row1= table1.insertRow(rowCount1);


        var arr= [];


       for(count = 0; count < rowCount1; count++)
       {    
            arr.push(table1.rows[count].cells[1].innerHTML);          
       }


       arr.shift();
       return arr;

    } 

    function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(int count = 0; count < arrCount; count++)
        {    
             //totalWorth= totalWorth+ returnedArr[count]; 

            document.write(returnedArr[count]);
            //debugger;
        }

        //return totalWorth;
    }

</script>

</head>
<body>
... (continued)

Update: (Modified the ShowWorthSum function)

 function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(count = 0; count < arrCount; count++)
        {    
             totalWorth= totalWorth+ returnedArr[count]; 

        }

        return totalWorth;
    }

Answer №1

One issue arises from not initializing the variable count properly. Try the following:

for(var count = 0; count < totalCount; count++){ ...

In JavaScript, remember to always declare your variables using var, regardless of whether it is a string or an integer.

Answer №2

Make sure to omit 'int' from your for loop declaration. Instead of:

for(int count = 0; count < arrCount; count++)

use:

for(count = 0; count < arrCount; count++)

Additionally, be aware that if your loop iterates beyond the number of elements in your array, it may return 'undefined' results. In your case, you have six elements but are looping a fixed total of 10 times. This means that anything past the 6th element will correctly output as 'undefined'.

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

Achieving CommonJS imports compilation with Typescript

In my TS file, I've included a 3rd party package using import XXX { YYY, ABC, 123 } from 'XXX'; While it compiles to CommonJS without any issues, I'd prefer to have it compiled to an ESModule instead. I tried changing the target and mo ...

Transferring information to modal without using AngularUI

I'm currently working on an Angular application and facing an issue with passing data from my controller to a modal. Here is the HTML code on my index page: <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> ... </head> & ...

Adjusting the CSS class name based on the screen size and applying styles to that class only during the "onload" event

The website I am currently developing can be found at . It is built on WordPress using the Avada theme and everything seems to be functioning correctly. The image move up effect on this site is achieved with the following JavaScript: window.onload = funct ...

Is Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

Having trouble with adding a listener or making @click work in VueJS?

Apologies for my limited experience with Vue. I am currently facing an issue where one of my click functions is not working as expected for multiple elements. The click event is properly triggered for the #app-icon element. However, the function is not be ...

The variable maintains the same value both inside and outside of the loop

I have a list of objects that provide information to a variable, which creates "markers": var markers = [ //testPOW { mesh: ["campDome","POW"], color: iconRed, location: {lat: 43.30985465943113, lng: 11.898409657895801}, visible: true, id: "TestPO ...

Managing asynchronous tasks that do not save their outcomes within the application state

Upon discovering a requirement within a vanilla JS webapp that necessitates a single JSON "definitions" object for rendering, I realized that the definitions are to be loaded through an HTTP request at the start, then read, parsed, and passed down to anoth ...

Adjusting ArrowHelper Width in Three.jsLooking to change the size of an Arrow

I have been attempting to adjust the width of pink lines on this jsfiddle link: animation of object In my code, I am defining local basis vectors as follows: // Defining local vector axis of plane var thetadir = new THREE.Vector3(1, 0, 0); var phidir = ...

Issues encountered when executing unit tests using karma

I encountered these issues in the logs. Seeking advice on how to proceed. Thank you. I've attempted uninstalling and reinstalling phantomjs, clearing out my node modules and bower component directories. Everything was functioning as expected before, a ...

Is there a way to enable Tail Recursion Optimization in TypeScript?

const isPositive = (n: number) => n > 0; function fitsIn(dividend: number, divisor: number, count: number, accum: number): number { if (accum + divisor > dividend) { return count; } return ...

When attempting to access injected services from the effect(), they appear to be empty

Upon receiving a notification, represented as a signal object, I utilize a facade service that not only returns the object but also includes a variety of methods. When new data is received, I analyze within the constructor using an effect whether the noti ...

Accessing a component's function from an HTML view in a Vue application

I seem to be stuck in a tricky situation with Vue logic. I have a "list" component that retrieves results from an ajax call. The issue arises when I try to incorporate a search field. Here is what I currently have: search.vue <template> <div> ...

Unable to find the designated ./uploads directory while attempting to upload a file in Express JS

I'm currently working on a project with the following structure: -app -uploads -client - dropzone.js -server.js My goal is to upload a file using dropzone js, Express JS, and React JS. However, whenever I try to drop a file in ...

Shared codes are compatible with both C and Javascript programming languages

Within the scope of this project, data will be retrieved from the server in either JSON or XML format. There are two separate client applications that will handle the data processing, with one being web-based and written in JavaScript, while the other is ...

Sharing server object in expressJS with another file through module.exports

As I work on my expressJS app, I encountered a situation where I needed to share the server object with another file. To achieve this, I decided to create the server in my app.js file and then expose it to one of my routes. var server = http.createServer( ...

What is the most efficient method for finding a match in a large list of words using ActionScript 3?

Currently, I am working on a word matching game where players have to form words using the entire English dictionary. To ensure efficient gameplay, I need to implement an algorithm in AS3 that quickly checks if the player's word is valid by searching ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

Retrieve the data stored in an array of objects

code props.thumbnails.forEach(value=>{ console.log(value.photo.thumbnail_url); }) error TypeError: Cannot read property 'thumbnail_url' of undefined Trying to loop through props.thumbnails array and access the thumbnail_url pro ...

Solving Cross-Origin Resource Sharing problem in an Express JS application

I have encountered a CORS error while using this code, despite having applied the necessary cross-origin headers. I am seeking guidance on how to resolve this issue. var express = require('express'); var bodyParser = require('body-parser&ap ...

I'm new to Angular and I'm wondering how to close the panel by clicking on the 'x' button and also by clicking on the screen. Can anyone help me with this

Below is the HTML code I use for my button: <button class="btn btn-outlined " ng-click="vm.showCommentBox1()">Notify All</button> <div class="comment-box custom saveAll" ng-if=""><div class="panel panel-default"> ...