Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

JavaScript While Loop and ">"

  • 11-02-2014 04:47PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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