Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Basics : The while loop

Thursday, October 7, 2021

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.









5 comments:

  1. i am Like your blog is a greet info this artical
    Andrew Polworth

    ReplyDelete
  2. Hey there! We are a reliable company https://essaysrescue.com/writemypapers-org-review/ to depend on if you have a literature review assignment because we work with highly qualified and experienced writers. Apart from that, our writers are competent to handle any order within a specified deadline. Therefore, it is possible to get prompt assistance for someone looking for urgent solutions with their assignments.

    ReplyDelete
  3. 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. casinoschileonline.com Therefore, there's a potential for an infinite loop.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete

Search This Blog