Js Loop While in JavaScript
? JavaScript while Loop
The while loop repeats a block of code as long as a specified condition is true.
? Syntax
while (condition) { // code to be executed repeatedly}Before each iteration, the condition is evaluated.
If the condition is
true, the loop runs.If the condition is
false, the loop stops.
? Example: Basic while Loop
let i = 0;while (i < 5) { console.log("Count: " + i); i++; // increment to avoid infinite loop}Output:
Count: 0Count: 1Count: 2Count: 3Count: 4? Important: Avoid Infinite Loops
If the condition never becomes false, the loop will run forever!
while (true) { // This will run infinitely unless broken out}Use break or update conditions properly.
? Example: Using break to Exit Loop
let i = 0;while (true) { console.log(i); i++; if (i === 3) { break; // exit loop when i is 3 }}Output:
012Would you like examples for do...while or for loops next?