Tech Junkie Blog: JavaScript Basics : The while loop

Thursday, April 20, 2017

JavaScript Basics : The while loop

The while loop statement in JavaScript simply executes a statement block until a condition is not true anymore the syntax for the while loop is as follow

while (expression is true)
{
     execute these statements
}

The while loop is an iterative loop if the condition is true and the statements are executed, it starts at the top of the loop again and executes until the expression is false.  Therefore, there's a potential for an infinite loop.



Here is an example of a while loop:

var countdown = 10;

while (countdown > 0) {
    console.log(countdown);
    countdown--;
}

console.log("Happy New Year!");

The code above simulates a new years count down which we are familiar with, the loop tests to see if countdown is greater than zero or not.  If countdown is greater than zero then we continue to execute the loop else we exit the loop.

Here is the output:
























Now let's see how this loop can turn into an infinite loop if the exit condition is never met!

var countdown = 10;

while (countdown > 0) {
    console.log(countdown);
    countdown--;
    countdown++;
}

console.log("Happy New Year!");

The code above decrements the countdown variable which is what we used to test our expression then increments it back therefore not changing the value at all and the expression always evaluates to true.  Hence, we have the countdown from hell!  Stuck at 10!  Never getting to "Happy New Year!" which is waiting patiently outside the while loop.  Poor "Happy New Year!" , my heart bleeds for you.


No comments:

Post a Comment