javascript while loop not functioning properly

Can someone assist me with troubleshooting this while loop issue?

<script type="text/javascript">
     var num = window.prompt("Please enter a score");
     var sum, average;
     var count=0;
     while (num > 0) {
         sum += num;
         count++;
     }
     average= sum / count;
     document.write(average); </script>

I'm encountering an issue with this loop as it doesn't seem to work even when inputting numbers greater than 0. Any suggestions on what might be causing this problem?

Answer №1

To easily find the solution to your problem, make sure to thoroughly comment your code and review each step along the way.

 <script type="text/javascript>
     //Start by declaring a variable chosen by the user
     var num = window.prompt("enter score");
     //Initialize counters
     var s, a;
     //Variable to keep track of loop iterations
     var count=0;
     //Loop continuously while num is greater than 0
     while (num > 0) {
         //Add n to s (Note: the origin of n is undefined) since s is not initialized
         s += n;
         //Increment count by one
         count++;
     }
     //Calculate the average and assign it to a
     a = s / count;
     //Avoid using document.write as it will overwrite the existing content in the document
     document.write(a);
</script>

Remember to avoid using document.write() unless you fully understand its impact on your code. Additionally, consider optimizing your code by removing unnecessary lines.

EDIT:

The code has been revised by the user.

<script type="text/javascript">
     //Define and initialize the user input value
     var num = window.prompt("enter score");
     //Initialize sum variable (previously not initialized, should be "var sum = 0;")
     var sum;
     //Define and initialize the count variable
     var count=0;
     //Loop as long as num is greater than 0
     while (num > 0){
          //Add num to sum
          sum += num;
          //Increment count by one
          count++;
     }
</script>

It is recommended to enhance your understanding of JavaScript and carefully review your code step by step as shown above.

Answer №2

It seems like the n term in the while loop hasn't been defined previously, which could be causing an issue. Additionally, the condition while(num > 0) will continue looping indefinitely if the value of num never changes from 0. To make the loop count up to a certain number, you can use the following code:

while(count < num){
   s += n;
   count++;
}

I hope this solution helps you out!

Best regards,

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

Is there a way to retrieve cookie data from a component that has been rendered in _app.js using Next.js?

Within my next.js application, I have implemented a functionality where a hashed token from an OAuth2 provider is stored using cookies. Once the user completes the necessary steps, they are logged in and the cookie storing the token is set. The log in but ...

Setting up CORS on Spring Boot along with Spring Security: A Comprehensive Guide

I'm encountering an issue with CORS. Here's the security configuration I have: @Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired CustomUserDetailsService userDetailsServ ...

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

Dynamic inheritance in Node.js based on the version being used

Why does the code provided only function correctly in Node.js versions 5.x and 6.x, but not in versions 4.x and older? Is there a way to modify the code so that it can work across Node.js versions 0.10.x - 6.x? 'use strict'; var util = require ...

I keep getting double results from the Multiple Checkbox Filter

Currently, I am facing an issue with a checkbox filter on a product page that I'm developing. The filter is functioning correctly, but I encounter duplicate results when an item matches multiple criteria. For instance, if I select both 'Size 1&ap ...

jQuery efficiently handles large amounts of text data transfer (gradual loading)

The issue at hand: My website relies on jQuery AJAX (post) for navigation, meaning the page doesn't refresh every time a user moves to a different section. This setup requires me to fetch data using AJAX and present it dynamically. While this works w ...

Blurring isotopes within Google Chrome

While working with isotope in Google Chrome, I noticed that all items have the following CSS code: -webkit-transform: translate3d(properties); In Chrome, every even element [2,4,6,8,10,12,14...] appears blurred, whereas in Firefox everything looks normal ...

Generating progress bar in Javascript while exporting CSV fileCan JavaScript export CSV and

Looking for a way to add a progress bar while generating and serving a CSV file via ajax? The database-heavy process is causing a delay, so I need a loader on the screen that disappears once the task is complete. It should be done with ajax or stay on th ...

Error message: Unspecified service injected

I am currently working with 2 separate javascript files for my project. One is being used as a controller, while the other serves as a service. However, when I attempt to inject the service into the controller and access its function, an error message pops ...

Detecting if a value is less than zero

I wrote a bank script that verifies if the user's deposit amount is a positive integer. If it's not, I want to reject the transaction. Check out my code snippet below: <section id="pigBox"> <img src="images/pig.png" /> & ...

Click on link after animation has finished

I'm currently facing an issue with my script not functioning correctly. The code I'm utilizing is from a resource provided by Codyhouse to implement a 3D rotating navigation menu on my webpage. Essentially, when you click the hamburger icon, it o ...

How about making an Ajax request for each item in the array?

I have a task to perform Ajax calls for each item in an array and then trigger another function once all the calls are completed. Adding complexity, I am incorporating Papa Parse into making the Ajax call. This is the code snippet: getCsvData: function( ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

The Google Drive API in Node.js is notifying the deletion of files

I encountered an issue with the Google Drive API in my application. Even after deleting files from Google Drive, the listfiles function still returns those deleted files. Is there a solution to prevent this from happening? Below is the function of my API: ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

Bidirectional Communication between ExpressJS and Mongoose Models

Let's consider a scenario where we have a User model and a Book model in our express app, both referencing each other. How can mongoose middleware be utilized to ensure that both models stay synchronized when saving either one? It would be beneficial ...

Utilizing JavaScript to access and present results from a PHP file located on a separate server

UPDATE I have set the header of my php file as shown below: header("Access-Control-Allow-Origin: *"); Currently, this is the error I am seeing in my browser: "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Heade ...

Ways to identify which arrays within an object contain an element

This question is unique as it pertains to objects of arrays rather than arrays of objects. I am working with a data structure like the one below and my goal is to determine if any of the arrays inside the object have values. What I'm looking for is a ...

Pass data from a JavaScript array to PHP with AJAX

I have sought assistance both here and on stackoverflow in creating an invitation function. Within an AJAX-based search box, users can invite teams. Upon locating and selecting a team, it is stored in an array. However, I now need to access the data from t ...

Updating the chosen option using jQuery

Is there a way to change the currently selected option using jQuery? <select name="nameSelect" id="idSelect"> <option value="0">Text0</option> <option value="1">Text1</option> <option value="2" selected>Text ...