Member-only story
A while
loop in JavaScript is another type of loop statement that allows you to execute a block of code repeatedly as long as a specified condition is true. Here's the basic syntax of a while
loop:
Not a Medium member? Read this article here
while (condition) {
// code to be executed
}
- The
condition
is evaluated before each iteration of the loop. If the condition is true, the loop continues. If the condition is false, the loop terminates. - The
code to be executed
is the block of code that is executed as long as the condition is true.
Here’s an example of a while
loop that counts from 0 to 4:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
In this example, the variable i
is initialized outside of the loop, the condition checks if i
is less than 5, and the code inside the loop prints the value of i
to the console and increments i
by 1 after each iteration. The loop will execute 5 times, with i
taking on the values of 0, 1, 2, 3, and 4, and each value of i
will be printed to the console.
You can also use a while
loop to iterate over an array:
const numbers = [1, 2, 3, 4, 5];
let i = 0;
while (i < numbers.length) {
console.log(numbers[i]);
i++;
}