Ajlec12 Ajlec12 - 16 days ago 5
Javascript Question

Javascript loop stuck

When I am running this script it gets stuck on prompting the user for the first number. It seems to not be counting up x.

function doMath() {
for (var x = 1; x < 3; x = x + 1) {
var var1;
var var2;
var var2;
var num;
if (x = 1) {
var num = prompt("Enter first number please");
var1 = parseInt(num)
}
else if (x = 2) {
var num = prompt("Enter second number please");
var2 = parseInt(num)
}
else {
var num = prompt("Enter third number please");
var3 = parseInt(num)
return Math.min(var1, var2, var3);
}
}
}

Answer

There are a few issues with your code:
- In your for-loop x would only ever be 1 or 2 seeing that : (x < 3) which mean it would never return a result
- To check for equality in an if-statement you need == or === not = which is assignment
- You are re-declaring your variables every iteration of the loop, and thus losing any stored information
- return after the for-loop completes

Putting it all together:

function doMath() {
    var var1;
    var var2;
    var var2;
    var num;
    for(var x =1; x <= 3; x++){ //use x++ instead of x = x + 1 (easier to read) 
        if (x == 1) { //fix here
           var num = prompt("Enter first number please");
           var1 = parseInt(num)
        } else if (x == 2) { //and here
           var num = prompt("Enter second number please");
           var2 = parseInt(num)
        } else {
           var num = prompt("Enter third number please");
           var3 = parseInt(num) 
        }
    }

    return Math.min(var1, var2, var3);
}