Ajlec12
Ajlec12

Reputation: 45

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);
        }
    }
}

Upvotes: 0

Views: 81

Answers (3)

HenryDev
HenryDev

Reputation: 4953

You are not calling the function and not outputting the final result.

Here's a working solution. Hope it helps!

function doMath() {
    var var1;
    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);
}
document.write(doMath());

Upvotes: 0

JanR
JanR

Reputation: 6132

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);
}

Upvotes: 1

SpiderWasp42
SpiderWasp42

Reputation: 2656

See line:

if (x = 1)

You are not checking if x == 1 but instead are making an assignment x=1. The latter is always true which means the condition is always met and that is why your code keeps prompting the user. Similarly for the other conditionals. They are all assignments. Hope this helps!

Upvotes: 4

Related Questions