Javascript while loop
Created By: chatGPT
A
while
loop in JavaScript repeatedly executes a block of code as long as a specified condition is true
. This is particularly useful when the number of iterations is not known beforehand. Let's look at the structure of a while
loop: it consists of the while
keyword, followed by a condition enclosed in parentheses, and a block of code in curly braces.while (condition) {
// code to be executed
}
Here’s an example of a
while
loop that prints numbers from 1 to 5:let number = 1;
while (number <= 5) {
console.log(number);
number++;
}
In this example, the loop checks if
number
is less than or equal to 5. If so, it prints the current value of number
and increments it by 1. This process continues until the value exceeds 5.// Output:
// 1
// 2
// 3
// 4
// 5
It's important to ensure that the condition eventually becomes false; otherwise, the loop will run indefinitely, causing an infinite loop. For example, if we forgot to increment
number
, it would remain 1, and the loop would never terminate.let number = 1;
while (number <= 5) {
console.log(number);
// number++; // Missing increment leads to infinite loop
}
You should also be careful when defining the exit condition. Here’s another example where the condition is based on user input, using
prompt
:let input;
while (input !== 'exit') {
input = prompt('Type `exit` to stop the loop.');
console.log('You typed:', input);
}
This example will keep asking the user for input until they type
exit
. Each time the user inputs something, that value is printed to the console. The loop will terminate when they type exit
.// User types something
// Console logs the typed value
// Loop continues until 'exit' is typed.