Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

While Loops in Javascript

This article is associated with the following course
Introduction to Javascript

Loops in Javascript allow us to call a block of code many times over without having to write the same code over and over again.

For example, lets say we want to print out the number’s one two and three in the console.

console.log(1);
console.log(2);
console.log(3);

With loops we could reduce the amount of console logs we call.

About the while loop

The while loop is a loop that doesn’t define how much iterations will be done. Our while loop will continue to iterate over and over again until its condition is no longer met.

For example:

while(true) {
  console.log("Hello world");
}

Will run over and over again in the console indefinitely

For our scenario we will need to set a variable number equal to zero. and the condition inside our while loop will be that our variable must be less than 4 when we’re deciding whether or not we should enter the while loops block of code enclosed by curly brackets { }

Note that we have to increment our variable otherwise we’ll end up in an infinite loop where our variable is always equal to 0.

var i = 0;
while(i < 4) {
  console.log("This is iteration number: " + i");
  i++;
}

Using the break statement to leave a while loop early

We can leave a while loop earlier than our conditional value will allow using the break statement.

Using break we can leave the loop if i is equal to 2, even if our while loops condition states to go through the loop while i is less than 4

var i = 0;
while(i < 4) {
  console.log("This is iteration number: " + i");
  if(i === 2) {
    break;
  }
  i++;
}

Using the continue statement to avoid executing succeeding lines of code

We may want to iterate through our loop but go back to the beginning of the loop at an earlier point. We can use the continue statment to do this. To show this, lets increment our loop twice and not show our console.log

var i = 0;
while(i < 4) {
  if(i === 1) {
     i+=2;
     continue; // the code below this wont run when i = 1
  }
  console.log("This is iteration number: " + i);
  if(i === 2) {
    break;
  }
  i++;
}