totn JavaScript

JavaScript: While Loop

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

Description

In JavaScript, the while loop is a basic control statement that allows you to perform a repetitive action. You use a while loop when you are not sure how many times you will execute the loop body and the loop body may not execute even once.

Syntax

The syntax for the while loop in JavaScript is:

while (condition) {
   // statements
}

Parameters or Arguments

condition
The condition is tested each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated.
statements
The statements of code to execute each pass through the loop.

Note

  • You would use a while loop statement when you are unsure of how many times you want the loop body to execute.
  • Since the while condition is evaluated before entering the loop, it is possible that the loop body may not execute even once.
  • See also the break statement to exit from the while loop early.
  • See also the continue statement to restart the while loop from the beginning.

Example

Let's look at an example that shows how to use a while loop in JavaScript.

For example:

var counter = 1;

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

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

In this while loop example, the loop would terminate once the counter exceeded 5 as specified by:

while (counter <= 5)

The while loop will continue while counter <= 5. And once counter is > 5, the loop will terminate.

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

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