JavaScript While Loop

The while loop in JavaScript runs a piece of code over and over again until the given condition is false.

Comparing with the for loop, the while loop has a much better syntax and is mostly used when the number of iterations or loops that we need is not known.

Syntax

while (condition) {
    // Block of code to run
}
  1. Here, the condition given inside the parenthesis ( ) is checked every time before the block of code inside the loop runs.
  2. If, the condition is true, the given block of code runs. If it is false, the given block of code doesn’t run and the loop ends.

Note: Also check out our JavaScript 👉 JavaScript Loops lesson on an intro to loops if you are new to it.


Example 1

// Initializing the variable i=0
let i = 0;

while (i < 3) {
  console.log(`Current value of i is ${i}.`);
  // Update the variable
  i++;
}

Output

Current value of i is 0.
Current value of i is 1.
Current value of i is 2.

How while loop works in JavaScript? 🤔

Unlike the for loop, the while loop in JavaScript doesn’t have sections in it’s syntax where we can initialize a variable and update it. Therefore, we have to declare and update the variable ourselves.

IterationVariableCheck Condition (i<3)OutputUpdate (i++)
1sti=0trueCurrent value of i is 0.i=1
2ndi=1trueCurrent value of i is 1.i=2
3rdi=2trueCurrent value of i is 2.i=3
4thi=3falseNo output as the condition is false.i=4
Table explaining the while loop

Example 2

console.log("The multiple of 5 is given below:");

let n = 1;
let limit = 10;

while (n <= limit) {
  console.log(`5 X ${n} = ${5 * n}`);
  n++;
}

Output

The multiple of 5 is given below:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

Infinite While Loop 😵

while (true) {
  // This code block will run infinitely
}

let n = 2;
while (n < 10) {
  // This code block will run infinitely
}

The above code blocks will run infinitely, or in some compilers, will return errors.


In this way, a while loop is used to run a block of code multiple times and has a simpler syntax than the for loop.