Ad space (banner)
🟨JavaScript Lessons
Lesson 8 / 69

Loops (while Statements)

In this lesson you'll learn about repeating with JavaScript's while statement, and understand the difference from for statements so you can choose the right one. This is for people searching "JavaScript while statement usage" or "JavaScript while vs for."

A while statement repeats "for as long as the condition holds." It's written as while (condition) { ... }, and unlike a for statement, it's often used when the number of repetitions isn't known ahead of time. The basic rule of thumb: use a for loop when you already know the "ending condition," and a while loop when you "don't know when it will end."

The sample code loops only while the count variable is less than 5, increasing its value by 1 with count++ inside the loop. The condition is evaluated at the top of the loop every time, and the moment it becomes false, the loop exits and execution moves to the next line. Keeping this "the condition is checked every time" flow in mind makes it easier to understand.

A common stumbling block is forgetting to update the variable involved in the condition inside the loop, creating an "infinite loop." If you deliberately use a condition like while (true), you must make sure to include a break somewhere inside the loop to exit it. If the browser seems frozen, suspect this first.

In real development, while statements shine in situations where you don't know the end condition ahead of time — a game's main loop, or code that waits until a response comes back from a server. The idea behind while loops is also commonly used as the foundation for programs that wait for user input.

Besides the ordinary form that checks the condition first, there's also a do...while form that always runs the body at least once before checking the condition. This is useful for situations like "show a message at least once, then ask whether to continue."

To exit a loop early based on a condition, you can use break; to skip just that one iteration, you can use continue. These are important tools for controlling repeated processing in fine detail, and they work in both while loops and for loops.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)