JavaScript while Loop

It is a common one to perform repetitive tasks. This article explains the working mechanism of the JavaScript while loop, syntax, flow chart, and how to iterate over data to perform calculations on individual items. Additionally, we cover the infinite while loop and a relay-time complex example.

A while Loop in JavaScript is useful for repeating a code block or block of statements for a given number of times until a specified condition is False. This robust iterator will help you to loop over the data and implement complex logic for each iteration. A while loop is ideal when the number of iterations is unknown, and the loop depends on dynamic conditions.

The JavaScript while loop begins with the’ while’ keyword, followed by the condition. If the condition is True, statements inside it will execute. If it is false, it won’t run at least once. It means while loop may execute zero or more times.

JavaScript while loop Syntax

The syntax of the while loop is as follows:

While( Condition )
 {
   statement 1;
   statement 2;
    ………….
 }
It is the statement Outside the While

From the above syntax, the condition, also known as an expression, determines whether the JavaScript while loop should iterate or not. We must place the expression in a set of parentheses.

If the condition evaluates to True, the statement or group of statements within the curly brackets will execute. Once the expression becomes false, it will terminate and execute other statements outside the { } (after })

What are the key components of a while loop in js?

  • Condition: An expression that decides whether the JavaScript while loop iteration should run or terminate. Remember, if the expression is false initially, it won’t return anything from the code block. 
  • Code block: The code or multiple statements enclosed with the curly braces {}. As long as the while loop condition returns True, these lines will execute. We can name the execution of the code block as an iteration.
  • Iteration: Each loop is called an iteration. It starts from a while loop condition and ends at a }.  
  • Increment or Decrement Value: It is the most crucial component. If you miss it, it becomes an infinite while loop.

JavaScript while Loop flow chart

By now, you have the theoretical knowledge of the while loop; let us see a practical example for a better understanding. The flow chart of the while loop is as shown below:

While loop Flow Chart

How does a JavaScript while loop work?

Within the script, when the while loop is encountered,

  • It first evaluates the condition or expression of the while loop before the iteration starts.
  • If the test condition result is True, the statements within the { } will execute.
  •  Before the end of the loop, the Increment & Decrement Operator inside it will increase or decrease the value.
  • After the iteration completes, the JavaScript while loop will again evaluate the expression with the updated value.
  • This process will repeat until the while condition returns a Boolean false. Once it returns False, it will exit entirely from the loop { } and execute other statements outside the while loop.

NOTE: When we know the total number of iterations, use a for loop. If you are working with unknown iterations (dynamic cases, for example, user input), prefer a while loop.

The following example helps in understanding the working functionality of a while loop visually.

JavaScript while loop to print numbers from 1 to 5

In the example below, we declared a variable and assigned the value 1 to it. The while loop expression checks whether n is less than or equal to five.

Inside the while loop, we used a console.log() to print the n value at each iteration. In the next line, the increment operator increments the n value by 1. Once the value is incremented, it again checks the while loop expression with the updated value. The process continues until n becomes 6; the condition fails.

let n = 1;
while (n <= 5)
{
console.log(n);
n++;
}
1
2
3
4
5

The step-by-step execution process of the while loop is iteration-wise. Initially n = 1.

Iterationn ValueConditionConsole.log(n)n++
111 <= 5 (True)12
222 <= 5 (True)23
333 <= 5 (True)34
444 <= 5 (True)45
555 <= 5 (True)56
666 <= 5 (False)Loop stops 

JavaScript while Loop to find the sum of N numbers

This example will add the numbers from 6 to 10 and calculate their sum. It is a simple example to demonstrate the while loop. However, you can change the variable number value to 1, the condition from 10 to 20, or increment by two.

In this while loop program, we declared a number and total variables and initialized values to 6 and 0. By using it, the program will add those values up to 10.

<!DOCTYPE html>
<html>
<head>
    <title> Example </title>
</head>

<body>
    <h1> Example </h1>
<script>
    var number = 6, total=0;
    while (number <= 10)
    {
        total = total + number;
        number++;
    }
    document.write("Total = ", total);  
</script>
</body>
</html>

Here, our number = 6. It means, total = 6 + 7 + 8 + 9 + 10 = 40

JavaScript While Loop 1

Analysis

  1. In this code example, we defined the JavaScript while Loop with the condition (number <= 10). 
  2. The value inside the number variable (6) will be tested against the condition, i.e., (6 <= 10).
  3. If the condition results true, the number will add to the total. Otherwise, it will exit from the JavaScript iteration.
  4. After adding the value to the total variable, we used the ++ operator to increment the number value. After incrementing, the process repeats until the condition results False.
  5. It will continue executing until the number reaches 11.

Sum of even numbers

In the example below, the starting number is even, and inside the JavaScript while loop, we used the assignment operator to increment the i value by 2. So, every time, it returns an even number and is added to the sum variable.

let i = 2;
let sum = 0;
while (i <= 100)
{
sum += i;
i += 2;
}
console.log(sum);
2550

The other way is using an if statement to check whether i value is divisible by 2. If true, add that number to the sum variable.

let i = 1;
let sum = 0;
while (i <= 100)
{
if (i % 2 == 0)
{
sum += i;
}
i++;
}
console.log(sum);
2550

Print numbers in reverse order

In the example below, the n value starts at 10. Inside a JavaScript while loop, we used the decrement operator to decrease the n value by 1.

let n = 10;
while (n > 0)
{
process.stdout.write(n + " ");
n--;
}
10 9 8 7 6 5 4 3 2 1 

JavaScript while loop to traverse an array

In our previous examples, we showed the while loop to iterate over a range of numbers. However, a while loop is commonly used to traverse the items in an array and perform operations.

In the example below, we declared an integer array with five elements. The length function finds its length. Inside the loop, we multiply each array item by 2 and display the output.

The following tables show how the while loop traverses an array in iteration wise. The length of a given array is 5.

iIterationConditionn[i]Outputi++
010 < 5 (True)1010 * 21
121 < 5 (True)2020 * 22
232 < 5 (True)3030 * 23
343 < 5 (True)4040 * 24
454 < 5 (True)5050 * 25
565 < 5 (False)Loop stops  
let n = [10, 20, 30, 40, 50];
let i = 0
while (i < n.length)
{
console.log(n[i] * 2);
i++;
}
20
40
60
80
100

User Input Validation

For the example below, the prompt message allows the user to enter the ratings from one to 5. As some users may mistakenly enter wrong values, we have used a while loop with a condition stating that the rating should be between 1 and 5.

To do so within the JavaScript while loop, we use the logical or operator to join two conditions: stating the rating is less than one or greater than 5. If true, prompt the user saying you have entered a number out of range; otherwise, print the given rating number in the console.

Here, the prompt message inside the while loop will display recursively until the user enters any number between 1 and 5.

let rating = prompt("Rate us from 1 to 5:");
while (rating < 1 || rating > 5)
{
rating = prompt("Out of range");
}
console.log(rating);
3

JavaScript while loop iterating over Objects

In the example below, we have created a fruit object containing the fruit name as the key and the total stock as the value. In the next line, we used the Object.entries() function to convert the fruits object into an array of arrays. Each nested array is a combination of a fruit and a key. For instance [[Apples, 10], [Kiwis, 50],..].

The while loop iterates over the object entries where the first index position contains the information of a nested array (apple and its stock). Inside the while loop, we perform the array destruction to read the key and value.

const fruits = {
Apples: 10,
Kiwis:50,
Oranges: 32,
Bananas: 25
};

const entries = Object.entries(fruits);
let i = 0;

while (i < entries.length) {
const [key, value] = entries[i];
console.log(`We have ${value} ${key}.`);
i++;
}
We have 10 Apples.
We have 50 Kiwis.
We have 32 Oranges.
We have 25 Bananas.

JavaScript while loop to handle asynchronous data with API

Apart from the regular examples, we can use a while loop to handle the asynchronous data. When working with the APIs, we have to fetch the data repeatedly until a specific condition is met. The while loop helps repeatedly fetch and process the data. Since API calls are mostly asynchronous, we must combine the while loop with an async function.

To handle the API data, use the fetch() function with async and await. The example below uses a free API to fetch user information, including ID, Name, Email, and the Company name. 

async function getUsersData()
{
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users'
);
const users = await response.json();

users.forEach(user => {
console.log(user.id),
console.log(user.name);
console.log(user.email);
console.log(user.company.name);
console.log('---');
});
} catch (error) {
console.error("Oops, something went wrong:", error);
}
}

getUsersData();
1
Leanne Graham
Sincere@april.biz
Romaguera-Crona
---
2
Ervin Howell
Shanna@melissa.tv
Deckow-Crist
---
3
Clementine Bauch
Nathan@yesenia.net
Romaguera-Jacobson
---
4
Patricia Lebsack
Julianne.OConner@kory.org
Robel-Corkery
---
5
Chelsey Dietrich
Lucio_Hettinger@annie.ca
Keebler LLC
---
6
Mrs. Dennis Schulist
Karley_Dach@jasper.info
Considine-Lockman
---
7
Kurtis Weissnat
Telly.Hoeger@billy.biz
Johns Group
---
8
Nicholas Runolfsdottir V
Sherwood@rosamond.me
Abernathy Group
---
9
Glenna Reichert
Chaim_McDermott@dana.io
Yost and Sons
---
10
Clementina DuBuque
Rey.Padberg@karina.biz
Hoeger LLC
---

Here, the async informs JavaScript to wait. It allows the other functions’ website to run as they are while the data loads in the background.

The await pauses the function from moving to the next line without getting the data. If we fail to use await before getting the data, JavaScript moves to the next line.

The data was received in JSON format, including information about the user’s ID, name, email, and company name. From this, we must extract the required ones using keys.

How to parse a CSV Row using a JavaScript while loop?

The following example shows a sample approach to parsing the data from a CSV file. To make it easy, we hardcoded the three employees’ information.

const employees = [
"John,25, 100000",
"Tracy,30, 95000",
"Mike,40, 125000"
];
let index = 0;
while (index < employees.length)
{
const [name, age] = employees[index].split(",");
console.log({name, age: Number(age), Income: Number(age)});
index++;
}
{ name: 'John', age: 25, Income: 25 }
{ name: 'Tracy', age: 30, Income: 30 }
{ name: 'Mike', age: 40, Income: 40 }

Number Guess Game

This JavaScript while loop program allows the user to enter any number between 1 and 10. If the user enters any number less than 7, it displays too low. Number above 7 returns Too high. However, when the user enters 7, the console prints You guessed the secret number.

const number = 7;
let guess = 0;
while (guess !== number) {
guess = Number(prompt("Guess the number (1-10):"));
if (guess < number)
{
alert("Too low!");
}
else if (guess > number) {
alert("Too high!");
}
}
alert("You Guessed it!");

What is an infinite while Loop in JavaScript?

When working with a while loop, we must be careful with infinite loops. If we set a while loop condition to always true, it becomes an infinite loop.

Suppose you forget to increment or decrease the value inside the while loop code block. In that case, the condition becomes true, and the while loop will execute infinitely (also called an infinite loop). For example:

<!DOCTYPE html>
<html>
<head>
    <title> JavaScriptWhileLoop </title>
</head>

<body>
    <h1> JavaScriptWhileLoop </h1>
<script>
    var x = 1;
    while (x < 10)
    {
        document.write("<br\> Value From the While Loop is = " + x);
    }
</script>
</body>
</html>

Here, x is always 1 because we haven’t updated the value inside a while loop. It means x is always 1, it is less than 10, and the loop will execute infinitely.

JavaScript Infinite While Loop Example

How can we prevent an infinite while loop in JavaScript?

You have to ensure that the condition eventually returns to False. Every while loop has to use either an increment or a decrement operator to increase or decrease the value so that the expression becomes false.

Let us add the increment operator (x++) inside the while loop to the above example.

<!DOCTYPE html>
<html>
<head>
    <title> Sample </title>
</head>

<body>
    <h1> Example </h1>
<script>
    var x = 1;
    while (x < 10)
    {
        document.write("<br\> Value = " + x);
        x++;
    }
</script>
</body>
</html>

Now, when it reaches 10, the condition will fail. Let us see the output.

Solve an Infinite While Loop in JavaScript

JavaScript while loop True condition

The other common reason is an intentionally infinite while loop to accept the user inputs. The syntax is

while (true) {
//code
}

The following examples use a Boolean True as the while loop condition, which means it always returns True. In such a case, we use the break statement to terminate the loop.

The example below allows the user to enter a password. If the password length is greater than or equal to 6 characters, the script returns a message, and the break statement will exit the loop. Otherwise, an alert message displays with the information. The process continues until the user enters 6 or more characters.

while (true) {
let password = prompt("Enter a password:");
if (password.length >= 6) {
console.log("Password accepted.");
break;
}
alert("Error: Password too short!");
}

Nested while loop in JavaScript

When we place one while loop inside another is called a nested loop, and this scripting language allows this approach. Whether you are working on gaming or data science projects, we have to use nested while loops to iterate over rows and columns in multidimensional data.

In the example below, we declare the matrix. The outer while loop helps to reiterate the matrix row items. The nested while loop iterates over the matrix columns. Within the nested loop, we use the log() function to print the row number, column number, and the value at that position to the console.

const matrix = [
[10, 20],
[30, 40],
[50, 60],
[70, 80]
];
let row = 0;
while (row < matrix.length) {
let col = 0;
while (col < matrix[row].length) {
console.log('Row:', row, 'Column:', col, matrix[row][col]);
col++;
}
row++;
}
Row: 0 Column: 0 10
Row: 0 Column: 1 20
Row: 1 Column: 0 30
Row: 1 Column: 1 40
Row: 2 Column: 0 50
Row: 2 Column: 1 60
Row: 3 Column: 0 70
Row: 3 Column: 1 80

JavaScript while loop break

This scripting language allows you to use the break and continue statements within the while loop. The break statement helps to terminate or exit the while loop completely. Using the if statement along with the break, iterations will end when the condition is met.

The example below demonstrates the break statement in a while loop. Here, we initialized the number to 1. Next, the while loop iterates from 1 to 10. Next, we used the if statement to check the condition whether the i value equals 4. If True, the break statement will terminate the loop without printing 4 and the other numbers after that.

let i = 1;
while (i <= 10) {
if (i === 4) {
break;
}
console.log(i);
i++;
}
1
2
3

Login attempts example

The above example is a simple one to demonstrate the break statement in a JavaScript while loop. However, at the production level, we can use a combination of a while loop and a break statement for login attempts, username validation, and password validation.

The example below allows the user to enter the password. The while loop checks whether the total number of attempts is below 5 and the user is not logged. Within the while loop, the if statement checks whether the password matches the original. If so, set the flag to true and print a message that the login was successful. After the five attempts, display the account lock message.

let attempts = 0;
const maximum = 5;
let flag = false;
while (attempts < maximum && !flag) {
attempts++;
let password = prompt("Enter a password:");
if (password === "admin123")
{
flag = true;
console.log("Login Successful")
}
}
if (!flag) {
console.log("Account locked");
}

JavaScript while loop continue

In contrast to the break statement, the continue statement skips the current iteration and jumps to the next one.

The example below demonstrates the break and continue statements in a while loop. Here, we initialized the number to 1. Next, we used two if statements to check the conditions. 

  • If the number equals three, the continue statement will skip printing that number and move to the next iteration.
  • If the number equals 6, the break statement will exit from the {}.
<!DOCTYPE html>
<html>
<head>
</head>

<body>
<script>
    var number = 1;

    while (number <= 10)
    {
      if(number == 3)
      {
        number++;
        continue;
      }
      document.write("<br\>" + number); 
      if (number == 6) 
      {
        break;
      }
      number++;
    } 

</script>
</body>
</html>
1
2
4
5
6

NOTE: Please refer to the Do While and the difference between while and do while articles.