While Loop

What are Loops?

While Loop Loops are useful when you have to execute the same lines of code repeatedly, for a specific number of times or as long as a specific condition is true.

Suppose you want to run a particular code for 100 times Of course, you will have to copy and paste the same code 100 times. Instead, if you use loops, you can complete this task in just 3 or 4 lines.

There are four types of loops in JavaScript.

  1. for loop
  2. while loop
  3. do-while loop
  4. for-in loop

In this article we learn about While Loop

The whileloop that runs as long as a given condition is true. The loop will only end once the condition is evaluated False.

while (condition) {
  // code block to be executed
}

Example:

let n = 0 
while(n < 5) {  // condition here is true 
  console.log(n) 
  n++ // same as n = n + 1 
} 
0
1
2
3
4

Example Explained:

On its 1st iteration, it will log the value of which is 0 then add one to it. n = 1

Condition: true ;

On its 2nd iteration, it will log the value of which is 1 then add one to it. n = 2

Condition: true;

On its 3rd iteration, it will log the value of which is 2 then add one to it. n = 3

Condition: true;

On its 4th iteration, it will log the value of which is 3 then add one to it. n=4

Condition: true;

On its 5th iteration, it will log the value of which is 4 then add one to it. n=5

Condition: false;

Why is it false means n is no longer less than 5, but it is now equal to 5. The loop will then stop executing, and that’s the end of the while loop.

fullstackadda/pointtoremember
  1. The while statement is a loop that runs as long as a given condition is true.
  2. While loop will only end once the condition is evaluated False.
While Loop