One of the key features of JavaScript is a loop: it makes a particular action perform repeatedly, saving you time. All JavaScript loops can be split into two categories: for loops and while loops. JavaScript for loops are again divided into three types: the general for loop, a for/in loop and a for/of loop.

The while loop JavaScript coders use can be of two types: while loop and do/while loop. In this tutorial, you will read about the basic syntax and usage of the JavaScript while loop. We will also explain how it differs from the do/while loop.

while Loop JavaScript: Main Tips

  • The while loop executes a block of code as long as the defined condition is true.
  • You can also use a do while JavaScript loop. It will execute the code once even if the condition is false.
  • You should remember to set the variable to be increased in order to avoid an infinite loop.

Syntax Rules

When you’re writing a while loop JavaScript syntax rules should always be in your mind. It is essential you write it correctly, otherwise you might not be able to achieve the results you want. Take a look at the standard while loop JavaScript syntax:

while (condition) {

code that will be executed

}

In the example below, you can see (i < 10) is set as the condition. This means that the code in the loop will run over and over again, as long as the variable i is less than 10:

Example

while (i < 10) {      
  example += "Loop counter: " + i;      
  i++;
}

#javascript #programming #while loops

Learn While Loops In JavaScript | Beginner JavaScript Tutorial | 2020
1.20 GEEK