Automating Tasks: JavaScript Loops

Stop repeating yourself! Discover how to make your code do the hard work for you by mastering the core looping structures in JavaScript.

Lesson ProgressStep 1 of 7

console.log(1);

console.log(2);

console.log(3);

0 1 2

...waiting... ❓

Run once! 🚀

Automation Unlocked!

0 EXP

Hello! Let's see how JavaScript handles repetitive tasks, so you don't have to copy and paste code.

console.log(1);
console.log(2);
console.log(3);
// This is so repetitive!

The `for` Loop: The Counter

The `for` loop is your go-to tool when you know exactly how many times you want a task to run. It's like telling your program, "Do this 10 times."

It has a very specific syntax with three parts:

for (initialization; condition; final-expression) {
  // code to execute
}
  • Initialization: `let i = 0` - Runs once at the very beginning. Creates a counter variable.
  • Condition: `i < 10` - Checked *before* each iteration. If true, the loop runs.
  • Final-expression: `i++` - Runs *after* each iteration. Updates the counter.

System Check

Which part of a `for` loop runs only *once* at the very beginning?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

✍️
Syntax Master

Correctly construct the syntax for a `for` loop.

🧠
Logic Whiz

Correctly identify the use cases for each loop type.

🚦
Control Expert

Successfully use `break` or `continue` to manage loop flow.

Mission: Optimize the Search

This loop finds the first number divisible by 7. But it's inefficient—it keeps checking even after finding the answer. Add the correct keyword to make it **stop** as soon as `found` is set.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Match the Loop Logic

Drag the descriptions into the correct order to match the loops: 1. `for`, 2. `while`, 3. `do-while`.

Runs as long as a condition is true (e.g., game loop)
Runs a known, specific number of times (e.g., 0 to 9)
Runs at least one time, then checks a condition (e.g., menu)

Challenge: Complete the Syntax

Fill in the three missing parts of a standard `for` loop.

for (; ; ) { ... }

Consult A.D.A.

Community Holo-Net

Automate Everything: A Deep Dive into JavaScript Loops

In programming, one of our core principles is **DRY (Don't Repeat Yourself)**. If you find yourself writing the same line of code multiple times, there's almost certainly a better way. In JavaScript, that better way is almost always a **loop**. Loops are fundamental constructs that allow you to execute a block of code repeatedly, saving you time, reducing errors, and making your code more powerful.

1. The `for` Loop: The Counter

The `for` loop is the most common loop you'll encounter. It's perfect for when you **know in advance** how many times you want to iterate. Its syntax is composed of three parts, separated by semicolons:

  1. Initialization: Runs once before the loop starts. Typically where you declare a counter variable (e.g., `let i = 0`).
  2. Condition: Checked *before* every iteration. If it evaluates to `true`, the loop's code block runs. If `false`, the loop stops.
  3. Final Expression (Increment): Runs *after* every iteration. This is where you update your counter (e.g., `i++`).
// Prints numbers 0 through 4
for (let i = 0; i < 5; i++) {
  console.log("The count is: " + i);
}
// Output:
// The count is: 0
// The count is: 1
// The count is: 2
// The count is: 3
// The count is: 4

2. The `while` Loop: The Sentinel

The `while` loop is simpler. It has only one part: a **condition**. The loop will run *as long as* the condition remains `true`. This is ideal for situations where you **don't know** how many iterations you'll need, such as waiting for user input, processing a file, or running a game's main logic.

let gameIsRunning = true;
let energy = 10;

while (energy > 0) {
  console.log("Player attacks! Energy left: " + energy);
  energy--; // Crucial: You must update the condition variable!
}
console.log("Game over.");

Warning: If you forget to update the variable in the condition (like `energy--`), the condition will *never* become false, and you will create an **infinite loop**, crashing your browser.

3. The `do-while` Loop: The Doer

The `do-while` loop is a variant of the `while` loop with one critical difference: the condition is checked *after* the code block runs. This means a `do-while` loop is **guaranteed to execute at least one time**, no matter what.

This is perfect for prompting a user with a menu. You want to show the menu at least once *before* you check if they chose the "exit" option.

let choice;

do {
  // This code runs at least once
  choice = prompt("Enter a command (or 'exit' to quit):");
  console.log("You typed: " + choice);
} while (choice !== "exit");

console.log("Exiting program.");

4. Modern Iteration: `for...of` and `for...in`

Modern JavaScript introduced easier ways to iterate over data structures:

  • for...of: The new standard for iterating over **iterables** like Arrays, Strings, Maps, and Sets. It gives you the **value** of each item directly. It's clean and simple.
  • for...in: Used to iterate over the **enumerable properties** of an **object**. It gives you the **key** (or index) as a string, not the value.

✔️ `for...of` (Values of an Array)

const colors = ['red', 'green', 'blue'];
for (const color of colors) {
  console.log(color);
}
// Output: "red", "green", "blue"

✔️ `for...in` (Keys of an Object)

const user = { name: 'Ada', age: 30 };
for (const key in user) {
  console.log(key + ": " + user[key]);
}
// Output: "name: Ada", "age: 30"

Warning: Do not use `for...in` to iterate over an Array. It can be slow and iterate over inherited properties, leading to unexpected bugs. Use `for...of` or a standard `for` loop for arrays.

5. Controlling the Flow: `break` and `continue`

Sometimes you don't want to just let a loop run its course. You can control its execution with two keywords:

  • break: **Terminates the loop entirely.** As soon as the code hits `break`, it jumps out of the loop and continues with the code *after* the loop. Perfect for finding the first match in a search.
  • continue: **Skips the current iteration.** It stops the current cycle and jumps straight to the *next* one (or the increment step in a `for` loop). Useful for skipping over bad data.
for (let i = 0; i < 10; i++) {
  if (i === 3) {
    continue; // Skip the number 3
  }
  if (i === 7) {
    break; // Stop the loop when we hit 7
  }
  console.log(i);
}
// Output: 0, 1, 2, 4, 5, 6
Key Takeaway: Choose the right loop for the job. Use `for` for known counts, `while` for unknown conditions, `do-while` to always run once, and `for...of` to iterate over array values.

JavaScript Loops Glossary

Loop
A programming construct that repeats a block of code as long as a certain condition is met.
Iteration
A single pass or execution of the code block inside a loop.
`for` loop
A loop with three parts: `(initializer; condition; final-expression)`. It is ideal for when the number of iterations is known beforehand.
`while` loop
A loop that executes a code block as long as a specified condition evaluates to `true`. The condition is checked *before* each iteration.
`do-while` loop
A loop that executes a code block *at least once*, then continues to run as long as a condition is `true`. The condition is checked *after* each iteration.
`for...of`
A modern loop for iterating over the **values** of an **iterable** object (like an Array, String, or Map).
`for...in`
A loop for iterating over the **enumerable property keys** (as strings) of an **object**.
Infinite Loop
A loop whose condition never becomes `false`, causing it to run endlessly and crash the program.
`break`
A keyword that immediately **terminates** the entire loop it is in.
`continue`
A keyword that **skips** the rest of the current iteration and proceeds to the next one.
Nested Loop
A loop placed inside the code block of another loop. The inner loop will run to completion for *each iteration* of the outer loop.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of web development experts, who have years of experience teaching JavaScript and building robust web applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest ECMAScript specifications and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!