While Loop

The while loop is a type of loop that allows you to repeat a block of code as long as a specified condition is true. The syntax of a while loop in JavaScript is:

Loading Code . . .

The loop will continue to run as long as the condition is true. Once the condition becomes false, the loop will exit, and the program will move on to the next line of code.

Here's an example of a simple while loop that counts from 1 to 5:

Loading Code . . .

In this example, the loop will run as long as count is less than or equal to 5. The console.log() statement inside the loop will print the current value of count, and then count will be incremented by 1 using the count++ statement.

The output of this code will be:

Loading Code . . .

It's important to be careful when using a while loop, as it can potentially result in an infinite loop. An infinite loop is a loop that never exits because the condition is always true. This can cause your program to crash or become unresponsive. To avoid infinite loops, always make sure that the condition in your while loop eventually becomes false.


In the exercises below, you'll practice using the while loop.

You can see a while loop with numbers from 1 to 10. Your mission is to use the console.log() method to print the even numbers.

Loading...
Loading...
Loading...
Loading...
Loading...

© 2024 - ®Mewters