Loading...
Loading...

While Loop in JavaScript

The while loop in JavaScript allows you to execute a block of code as long as a specified condition evaluates to true. It's useful for repeating tasks when the number of iterations is not known in advance.

Basic Syntax of a While Loop

while (condition) {
    // code to be executed
}

In this syntax, the code block inside the while loop will be executed as long as the condition is true.

Example of a While Loop

let count = 0;

while (count < 5) {
    console.log("Count is: " + count);
    count++;
}

In this example, the loop will print the current value of count to the console until it reaches 5. The count++ statement increments the count by 1 in each iteration.

Using a While Loop for User Input

let input;

while (input !== "exit") {
    input = prompt("Enter something (type 'exit' to stop):");
    console.log("You entered: " + input);
}

This example demonstrates a while loop that continues to prompt the user for input until they type "exit". The input is then logged to the console.

Infinite Loops

Be cautious when using while loops, as it's easy to create an infinite loop if the condition never becomes false. For example:

let num = 0;

while (num < 5) {
    console.log(num);
    // Missing increment here will cause an infinite loop
}

This loop will run indefinitely since num is never incremented.

Conclusion

The while loop is a powerful tool in JavaScript for executing code repeatedly based on a condition. However, it's important to ensure that the loop will eventually terminate to avoid infinite loops.

0 Interaction
1.1K Views
Views
10 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home