Using While Loop to coding in Javascript/JS

This JavaScript tutorial explains how to use the while loop with syntax and examples.


In JavaScript, the while loop is a fundamental manipulate statement that allows you to operate a repetitive action. You use a while loop when you are now not positive how many times you will execute the loop body and the loop body can also not execute even once.


The syntax for the while loop in JavaScript is:

while (condition) {
   // statements

Parameters or Arguments

condition The circumstance is examined each pass via the loop. If circumstance evaluates to TRUE, the loop body is executed. If situation evaluates to FALSE, the loop is terminated. statements The statements of code to execute every omit via the loop.


You would use a whilst loop statement when you are not sure of how many instances you prefer the loop physique to execute. Since the whilst condition is evaluated before coming into the loop, it is viable that the loop physique might also no longer execute even once. See also the break announcement to exit from the while loop early. See also the proceed assertion to restart the whilst loop from the beginning.


Let’s seem at an instance that shows how to use a whilst loop in JavaScript.

For example:

var counter = 1;

while (counter <= 5) {
   console.log(counter + ' - Inside while loop on');

console.log(counter + ' - Done while loop on');

In this whilst loop example, the loop would terminate as soon as the counter surpassed 5 as designated by:

while (counter <= 5)

The while loop will proceed while counter <= 5. And as soon as counter is > 5, the loop will terminate.

In this example, the following will be output to the net browser console log:

1 - Inside while loop on
2 - Inside while loop on
3 - Inside while loop on
4 - Inside while loop on
5 - Inside while loop on
6 - Done while loop on