Video Lesson

Lesson Notes

Understanding the JavaScript while Loop

In this post, I’ll walk you through the basics of the while loop in JavaScript—what it is, how it works, and some pitfalls to watch out for.

What Is a while Loop?

A while loop repeatedly executes a block of code as long as a specified condition remains true. It’s a simpler alternative to the for loop when you don’t necessarily know how many iterations you need up front.

Syntax

1while (condition) { 2 // code to run each time the condition is true 3}

Step-by-Step Example

  1. Initialize a variable
    Before the loop starts, set up any variables needed for the condition:

    1let checker = 12;
  2. Write the while statement
    Use the while keyword followed by a condition in parentheses:

    1while (checker < 14) { 2 console.log(checker); 3 checker++; 4}
  3. What Happens

    • Check if checker < 14.
    • If true, run the code inside the block.
    • After running, update checker (with checker++) to eventually break out of the loop.
    • Repeat until checker is no longer less than 14.

Full Example

1let checker = 12; 2 3while (checker < 14) { 4 console.log("Current value:", checker); 5 checker++; 6} 7 8// Output: 9// Current value: 12 10// Current value: 13

Common Pitfalls

  • Infinite loops: If you forget to update the variable used in the condition, the loop will never end.

    1let i = 0; 2while (i < 5) { 3 console.log(i); 4 // missing i++; 5} 6// This will run forever!
  • Off-by-one errors: Make sure your condition and updates align so you don’t run one time too many or too few.

When to Use a while Loop

  • You don’t know how many times you need to iterate up front.
  • You want a simple, condition-based loop without initialization and increment in the header (as in a for loop).

Summary

  • A while loop runs as long as its condition is true.
  • Always ensure your loop variable is initialized and updated correctly.
  • Watch out for infinite loops and off-by-one mistakes.

AI Assistant

Sign In Required

Sign in and subscribe to use the AI assistant for instant help with your lessons.

Sign In

While Loop: Basics

Lesson on the `while` loop, where you'll learn how to create dynamic code that executes repeatedly based on conditions. Discover its syntax, practical examples, and common pitfalls to avoid, empowering you to write efficient and effective loops in your programming projects!

2m 26s

Course Content

0 of 32 lessons completed
6. Promises, Async and Await
0 of 0 completed
7. The DOM
0 of 0 completed