While Loop
The while
loop is used to execute a block of code repeatedly as long as a specified condition is true
. It is a type of entry-controlled loop, which means the condition is checked before the block of code is executed.
Here is the syntax of the while
loop:
while (condition) {
// Code block to be executed
}
- The
condition
is evaluated before each iteration. If the condition istrue
, the code block inside the loop is executed; otherwise, the loop terminates. - The code block inside the
while
loop will continue to execute until the condition evaluates tofalse
. - If the condition is
false
from the beginning, the code block inside the loop will not execute at all. - The
condition
is crucial in awhile
loop to prevent an infinite loop.
Example
Here is an example of using a while
loop to print numbers from 1
to 5
:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
In the example above, the while
loop checks if the variable i
is less than or equal to 5
. If the condition is true
, it executes the code block inside the loop, prints the value of i
, and increments i
by 1
after each iteration.
Nested While Loop
You can nest while
loops inside each other to create complex patterns or iterate over multi-dimensional arrays. When you nest loops, the inner loop is executed multiple times for each iteration of the outer loop.
Here is an example of using nested while
loops to create a multiplication table:
let i = 1;
while (i <= 10) {
let j = 1;
while (j <= 10) {
console.log(`${i} * ${j} = ${i * j}`);
j++;
}
i++;
}
In the example above, the outer while
loop iterates over the numbers from 1
to 10
. For each iteration of the outer loop, the inner while
loop iterates over the numbers from 1
to 10
and prints the multiplication table for the current number.
Infinite Loop
We talked about infinite loops in the previous section. Let's see an example of an infinite loop using a while
loop:
let i = 1;
while (i <= 5) {
console.log(i);
i--;
}
In the example above, the loop variable i
is initialized to 1
, and the loop condition i <= 5
is always true
. The decrement expression i--
decreases i
by 1
after each iteration. Since i
is always less than or equal to 5
, the loop will run indefinitely.
In the next section, we will learn about the do...while
loop in JavaScript. Let's keep going! 🚀
Made with ❤️ by Fasakin Henry