JavaScript: While Loop

Profile picture for user arilio666

The while loop in javascript loops through the body of code until the condition is satisfied.

Syntax

while()
{
    // statements
}

Example:

let age = 1

while(age < 5)
{
    console.log("Age of " +age+ " is allowed!")
    age++
}

Output:

Age of 1 is allowed!
Age of 2 is allowed!
Age of 3 is allowed!
Age of 4 is allowed!
  • Here the while loop pertains to a condition based on the declared variable of age that we have initiated.
  • The age commences from 1 and goes up to the given state of age < 5, which should increase to 4.
  • After that, we increment the age every time the loop ends it checks the condition.
  • Returns back to the while body and executes the situation until it reaches 5 and checks, obviously not less.
  • So the loop breaks up, and the condition ends and comes out of the body.