Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

JavaScript While Loop and ">"

Options
  • 11-02-2014 5:47pm
    #1
    Registered Users Posts: 266 ✭✭


    I was wondering if anybody could tell me why the following while loop condition does not work in JavaScript:

    var num1 = 6, num2 = 3, result;

    while (num1 > 5)
    {
    num2 += 1;
    }

    result=num1+num2;
    document.write(result);

    I was expecting to loop through just once giving an output of 10

    Thanx for any help.


Comments

  • Registered Users Posts: 806 ✭✭✭Niall09


    Gerb68 wrote: »
    I was wondering if anybody could tell me why the following while loop condition does not work in JavaScript:

    var num1 = 6, num2 = 3, result;

    while (num1 > 5)
    {
    num2 += 1;
    }

    result=num1+num2;
    document.write(result);

    I was expecting to loop through just once giving an output of 10

    Thanx for any help.

    The reason it's not just giving one output, is because it's an infinite loop - num1 will always be greater than 5 in your piece of code above. num1 isn't modified in the code so each time the condition is evaluated, it will always be 6 > 5 which is true and so will enter the loop.


Advertisement