Struggling to pinpoint the issue in my JavaScript for-loop function

My JavaScript code calculates the average of numbers as they are entered by pressing the add button. The added numbers are displayed on the screen, and if no number is entered, an "empty string" message is shown. However, I am facing an issue where the "empty string" text continues to be displayed even after entering numbers.

Initially, the code worked correctly when numbers were provided manually without user input. But when I allowed users to enter numbers themselves, the average calculation started malfunctioning.

Here is a snippet of the problematic code:

<body>
    <h2>Average Function</h2>
    <p>Press the button below to add numbers to the array:<br>
        <button onclick="addNum()">Add</button>
    </p>
    <p id="numInArray"></p>
    <p id="average"></p>

    <!--JS Code-->
    <script>
        var grades = [];

        function addNum() {
            var grade = prompt("Add a number");
            grades[grades.length] = grade;
            document.getElementById("numInArray"). innerHTML =
            "Numbers in array are: " + grades;
        }

        var sum = 0;
        if (grades.length > 0) {
            for (index = 0; index < grades.length; index++) {
                sum += grades[index];
            }
            document.getElementById("average").innerHTML = sum/grades.length;
        } 
        else {
            document.getElementById("average").innerHTML = "Empty string";
        }
    </script>
</body>

Answer №1

Things to keep in mind:

  • Consider when the code is executed (function declaration versus execution)
  • Prioritize the order of operations
  • Understand and utilize scopes effectively

Here's an example showcasing some code revisions with explanatory comments:

<body>
  <h2>Average Function</h2>
  <p>
    Click the button below to add numbers to the array:<br />
    <button onclick="addNum()">Add</button>
  </p>
  <p id="numInArray"></p>
  <p id="average"></p>

  <!--JavaScript Code-->
  <script>
    // Initialize application by declaring reusable variables for each invocation of addNum function
    var grades = [];
    var sum = 0;

    // Set initial value for average display to "Empty array"
    document.getElementById("average").innerHTML = "Empty array";

    // Function executes only on user input
    function addNum() {
      var grade = prompt("Enter a number");
      // Use push method to append grade to grades array
      grades.push(grade);

      // Add entered number to sum after converting it to integer using parseInt
      sum += parseInt(grade);

      // Update DOM elements
      document.getElementById("numInArray").innerHTML = "Numbers in array: " + grades;
      document.getElementById("average").innerHTML = sum / grades.length;
    }
  </script>
</body>

A helpful tip: Write pseudo code outlining the steps of your application before diving into coding. In this case, focus on initialization and updates after user interactions.

Answer №2

When using the addNum() function, you are essentially expanding the size of your array without any additional functionality. The key is to include the summed values from addNum() and display them in the HTML. I have optimized your code with some suggestions:

  1. Avoid declaring variables with var and instead utilize const and let for better variable scoping.
  2. To insert new elements into an array, use Array.push().
  3. I have enclosed the static string Numbers in array are: within a <p> tag, which then contains another <p> element for displaying the numbers accordingly.
  4. When concatenating strings and numbers in JavaScript, make sure to convert them properly by using parseInt(). This method returns NaN if the initial non-whitespace character cannot be transformed into a number.

const grades = [];
function addNum() {
    const grade = prompt("Add a number");
    if(grade.length > 0){
        grades.push(grade);
    }
    document.getElementById("numInArray").textContent = grades;
    document.getElementById("average").textContent = findSum(); 
}
function findSum() {
    let sum = 0;
    for (index = 0; index < grades.length; index++) {
        sum += parseInt(grades[index]);
    }
    return sum > 0 ? sum / grades.length : "Empty string";
}
<h2>Average Function</h2>
<p>Click the button below to input numbers into the array:<br>
  <button onclick="addNum()">Add</button>
</p>
<p>The numbers in the array are: <span id="numInArray"></span></p>
<p id="average"></p>

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

Repetitive submissions of a form through Ajax post requests

Currently, I am utilizing this code to handle data sent via Ajax. Within the code, I am using the summernote editor. However, I have encountered an issue where if I submit the form while missing a required field, the form displays a 'required alert&ap ...

Discover if a specific string is present within a given array

I am looking for a way to determine if the term 'Computer Science' exists within an array that contains values such as 'Computer Application' and 'Computer Science'. Array ( [0] => Computer Application [1] => ...

Combining nested arrays into a single array using MongoDB

My current aggregation result consists of an array of two objects: [ { "immunizationDetails": [ [ "Rubella" ], [ "PCV13", "Tdap" ] ] }, { "immuni ...

Trigger an immediate repaint of a DOM element in the browser

Searching for a way to insert a large HTML markup into a DOM element that will take some time. This is why there's a need to display a preloader indicator before the process begins. Two blocks are involved: #preloader and #container. Initially, the pr ...

Raphael's path adorned with arrow-shaped tips

Recently delving into raphael.js, I am attempting to create an arrow head on a raphael path element (or draw an arrow from point A to point B). Here is the raphael path (line) that I have sketched from point A to point B on my canvas. Assuming that the val ...

Angular 11 - New Script Inserted into scripts Directory and Linked in angular.json Configuration

I just added a new script file in the src/assets/scripts directory and updated its path in the scripts section of angular.json. My question is: Will I need to restart ng serve for the changes to take effect the next time the application is run? Thank you ...

Having trouble with passing post data from jQuery ajax to a php page?

Attempting to retrieve post data using an alert() function, but encountering an issue where the data is not being passed to the PHP page. The result always shows {"success":false,"result":0} The goal is to transmit a password to the PHP page, hash it usin ...

What is causing me to encounter an additional hour when computing time differences in JavaScript?

I am attempting to create a simple time difference calculation by subtracting the end time from the start time. However, I am noticing that I am getting an extra hour in my result. I believe this may be due to my timezone being GMT+1. Regardless of the ti ...

Tips for changing the TextField variant when it receives input focus and keeping the focus using Material-UI

When a user focuses on the input, I'd like to change the variant of the TextField. The code snippet below accomplishes this, but the input loses focus. This means the user has to click again on the input to focus and start typing. import React, { useS ...

Using Three.js to rotate a camera-followed sphere in the scene

Currently, I'm developing a Three.js scene with a toy concept where I aim to track a sphere using a camera [demo]. However, I am facing an issue wherein I can't seem to get the sphere to "roll" without causing the camera to also rotate along with ...

Splitting a JSON array into two separate arrays of values using jQuery: a step-by-step guide

My AJAX script is pulling a JSON array from a PHP file. Here's the script: // jsonData fetched from inc/wip-data.php var jsonData = $.ajax({ url: 'inc/wip-data.php', dataType: 'json', }); The JSON array looks like this: [ { ...

Angular 4 keeps separate copies of common filters for individual pages

In my Angular application, I have implemented various custom filters on different report pages. Users are able to navigate between pages and customize filters for each page. I am looking to add a feature where these common filters will be maintained for ea ...

Does Parsley.js offer a way to configure so that the parsley-success field is not added to an input if it should be completely ignored?

Currently, I am excluding one input and adding the success class (which is fine with me) $('form').parsley({ excluded: '[data-parsley-sum-total="all"]' }); However, there are several other inputs without any validations that I do not wa ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Prevent jQuery from scrolling once the fixed image reaches the bottom of the page

I am struggling to figure out how to keep an image fixed at the top of the footer div while scrolling to the bottom of a webpage. My approach involved calculating the height of the footer in order to adjust the scrolling behavior by subtracting it from th ...

Is it possible to utilize X-Y coordinates as repositories for values beyond just X-Y coordinates themselves?

I am in the process of creating a tile-based grid and I need to expand the X-Y coordinates to include additional values for determining characteristics of each tile, such as resources (for example, food, water, stone, lumber) within a game context. Conside ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

How can Three.js help you identify whether a point lies on a given line?

Is there a way to determine if a specific point (x,y,z) lies on the line segment between two other points, pointA and pointB? I am looking for a boolean function that can efficiently solve this problem: pointA // random THREE.Vector3 pointB ...

Storing blank information into a Mongodb database with Node.js and HTML

Can someone please assist me with solving this problem? const express=require("express"); const app=express(); const bodyparser=require("body-parser"); const cors=require("cors"); const mongoose=require("mongoose"); ...

Tips for concealing passwords and email addresses in URLs within an Express application

http://localhost:3000/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e297918790dd878f838b8edf838081a2858f838b8ecc818d8f">[email protected]</a>&pass=abc123 what is the best way to conceal email addresses and ...