How to Write a While Loop in JavaScript ?
In JavaScript, a while
loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// code block to be executed while condition is true
}
The loop continues to execute the block of code within its curly braces ({}
) as long as the specified condition evaluates to true
. If the condition evaluates to false
initially, the block of code inside the loop will not be executed at all.
Example: Here, the while
loop continues to execute as long as the count
variable is less than 5
. Inside the loop, we log the current value of count
to the console and then increment count
by 1
in each iteration. Once count
reaches 5
, the condition count < 5
becomes false
, and the loop terminates.
Javascript
let count = 0; while (count < 5) { console.log( "Count:" , count); count++; // Increment the count by 1 in each iteration } |
Output
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
Contact Us