Automating Tasks with JavaScript Loops: For, While & Do-While
Stop repeating yourself! Discover how to make your code do the hard work for you by mastering the core looping structures in JavaScript.
console.log(0);
console.log(1);
console.log(2);
// ...so repetitive!
The 'for' Loop: The Counter
The for
loop is your go-to when you know exactly how many times you want a task to run. It combines an initializer (let i = 0
), a condition (i < 5
), and an incrementor (i++
) into one clean line. It's perfect for counting or iterating over arrays with a known length.
The 'while' Loop: The Sentinel
The while
loop is more flexible. It runs as long as a certain condition remains true. This is useful when you don't know the number of iterations in advance, such as waiting for user input or processing a data stream until it ends.
The 'do-while' Loop: The Doer
The do-while
loop is a variation of while
with one key difference: the code block is guaranteed to execute at least once. The condition is checked *after* the first run, making it ideal for situations like displaying a menu before asking for a choice.
Loop Control & Pitfalls
Be careful of infinite loops, where the condition never becomes false! You can also control loop execution with keywords like break
to exit a loop early or continue
to skip the current iteration and move to the next.
Practice Zone
Interactive Test 1: Match the Loop
Drag the loop type to its best description.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Build the 'for' loop
Rellena los huecos en cada casilla.
(let i = 0; i < 5; i++) {
console.log("Counting: " + i);
}
Practice Example: Code Editor
Complete the code in the editor to print numbers from 0 to 4 using a while
loop.
Loops in Action: Common Use Cases
Loops are fundamental building blocks in programming. Here are some real-world scenarios where choosing the right loop is key.
1. Iterating Over Arrays with `for`
The most common use for a for
loop is to go through each item in an array. Since an array has a known .length
, it's a perfect fit.
const fruits = ['🍎', '🍌', '🍒'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
2. Handling User Input with `do-while`
When you need to get valid input from a user, a do-while
loop ensures the prompt is shown at least once. The loop continues until the user provides a satisfactory answer.
let name;
do {
name = prompt("Please enter your name:");
} while (name === "");
3. Game Logic with `while`
Many simple games run on a main `while` loop. The loop continues as long as the game is active, processing player moves and updating the screen on each iteration (or "tick").
let gameIsRunning = true;
while (gameIsRunning) {
// handleInput()
// updateGameState()
// renderScreen()
}
Practical Takeaway: Choosing the right loop isn't just about making the code work; it's about writing code that clearly communicates its intent. Use `for` for known counts, and `while` or `do-while` for condition-based repetition.
JavaScript Loops Glossary
- Iteration
- A single pass or cycle through a block of code within a loop.
- Condition
- The logical expression that is evaluated before (or after) each iteration. The loop continues as long as this expression evaluates to `true`.
- for loop
- A loop structure that combines an initializer, a condition, and a final expression (like an incrementor) into one statement. Ideal for a known number of iterations.
- while loop
- A loop that executes its code block as long as a specified condition is true. The condition is checked *before* each iteration.
- do-while loop
- Similar to a `while` loop, but the code block is executed at least once before the condition is checked.
- Infinite Loop
- A loop whose condition never becomes false, causing it to run forever and potentially crash the program or browser tab.
- break
- A keyword used to immediately terminate the current loop and transfer control to the statement following the loop.