javascript

Loop Statements

Learn what loop statements are in JavaScript. Understand how to use for, while, and do...while loops to repeat actions and automate tasks in your code.

10 min read 8 sections Tutorial
Share

Loop statements help your computer repeat actions many times. Instead of writing the same code over and over, you write it once inside a loop. The loop then runs that code for you, as many times as you tell it to. Loops are super useful for tasks like counting, going through lists of items, or waiting for something to happen. They make your programs efficient and powerful.

Loop Statements

Loop Statements

A loop is a way to run the same set of instructions multiple times. Imagine you need to print a message 100 times. Without a loop, you would type console.log('Hello!'); 100 times. With a loop, you write it once, and the loop handles the repetition.

JavaScript offers different kinds of loops for different situations. The most common ones are for loops, while loops, and do...while loops.

What is a Loop?

A loop is a programming construct that executes a block of code repeatedly until a certain condition is met.

for Loop

Best for when you know exactly how many times you want to repeat something.

while Loop

Great for when you need to repeat as long as a condition is true, but you don't know how many times.

do...while Loop

Similar to 'while', but it always runs at least one time before checking the condition.

Loop Control

Special keywords like break and continue can change how a loop runs.

Repeating Actions with `for` Loops

Getting Started

Repeating Actions with `for` Loops

A for loop is often used when you know exactly how many times you want to repeat a task. It has three main parts inside its parentheses, separated by semicolons:

  1. Start: Where the loop begins (e.g., let i = 0).
  2. Condition: The rule that must be true for the loop to keep running (e.g., i < 5).
  3. Step: What happens after each repetition (e.g., i++ means add 1 to i).
javascript
1// This loop will run 5 times (for i = 0, 1, 2, 3, 4)
2for (let i = 0; i < 5; i++) {
3 // This code inside the curly braces runs each time
4 console.log('The current count is: ' + i);
5}
6
7// Output:
8// The current count is: 0
9// The current count is: 1
10// The current count is: 2
11// The current count is: 3
12// The current count is: 4

Watch out for Infinite Loops!

If your loop's condition never becomes false, it will run forever. This is called an infinite loop and can crash your program. For example, for (let i = 0; i < 5; i--) would be an infinite loop because i would keep getting smaller and always be less than 5.

The `while` Loop — Repeating While a Condition is True

The `while` Loop — Repeating While a Condition is True

A while loop keeps running as long as a specific condition is true. It's simpler than a for loop because you only give it a condition. The 'start' and 'step' parts need to be handled by you outside and inside the loop's curly braces.

This is useful when you don't know in advance how many times the loop needs to run. For example, you might loop until a user types a specific word.

javascript
1// Start our counter variable outside the loop
2let energy = 3;
3
4// The loop will run as long as 'energy' is greater than 0
5while (energy > 0) {
6 console.log('Player has ' + energy + ' energy left.');
7 // Decrease energy by 1 each time the loop runs
8 energy = energy - 1; // Or energy--;
9}
10
11console.log('Player ran out of energy!');
12
13// Output:
14// Player has 3 energy left.
15// Player has 2 energy left.
16// Player has 1 energy left.
17// Player ran out of energy!
✗ BadUsing `for` for unknown iterations (less clear)
let guess = '';
for (; guess !== 'secret'; ) {
// This part is missing, would be complicated
// guess = prompt('Guess the word:');
console.log('Wrong guess!');
}
✓ GoodUsing `while` for unknown iterations (clearer)
let guess = '';
while (guess !== 'secret') {
// In a real browser, this would ask the user for input
// For this example, we'll simulate a guess.
console.log('Wrong guess! Try again.');
guess = 'secret'; // Simulate user eventually guessing correctly
}
console.log('Correct! You guessed the word.');

Different Loops for Different Jobs

Different Loops for Different Jobs

Besides for and while, there's also the do...while loop and special loops for arrays. Each loop type is best for slightly different tasks. Choosing the right loop makes your code easier to understand and prevents mistakes.

The do...while loop is very similar to while, but it guarantees that the code inside the loop will run at least one time, even if the condition is false from the start.

`while` Loop (checks first)
// Condition is false from the start
let count = 0;
while (count > 0) {
console.log('This will not print.');
count--;
}
console.log('Loop finished (while).');
// Output: Loop finished (while).
VS
`do...while` Loop (runs once, then checks)
// Condition is false from the start
let count = 0;
do {
console.log('This will print once: ' + count);
count--;
} while (count > 0);
console.log('Loop finished (do...while).');
// Output: This will print once: 0\nLoop finished (do...while).

When to use `do...while`

Use a do...while loop when you need to run the code block at least once, even if the condition is false. A common example is asking for user input, then repeating if the input is bad.

Loops in Real-World JavaScript

Loops in Real-World JavaScript

Loops are fundamental for almost any program that handles lists of data. Think about a shopping cart, a list of users, or game items. You will use loops to go through each item, one by one, and do something with it. This is how you automate tasks over collections of data.

1

Create a list of items (an Array)

Most often, you will loop through an array, which is a list of values. Declare an array using square brackets [].

javascript
1const shoppingList = ['milk', 'eggs', 'bread', 'butter'];
2

Use a `for` loop to process each item

A for loop is perfect for arrays because you know how many items are in the list (its length). You can access each item using its position, called an index.

javascript
1for (let i = 0; i < shoppingList.length; i++) {
2 const item = shoppingList[i]; // Get the item at the current index
3 console.log(`Don't forget the ${item}!`);
4}
5// Output:
6// Don't forget the milk!
7// Don't forget the eggs!
8// Don't forget the bread!
9// Don't forget the butter!
3

Use `break` to stop a loop early

Sometimes you want to stop a loop before it finishes all its repetitions. The break keyword stops the loop immediately.

javascript
1for (let i = 1; i <= 10; i++) {
2 if (i === 5) {
3 console.log('Found 5! Stopping loop.');
4 break; // Exit the loop completely
5 }
6 console.log(i);
7}
8// Output:
9// 1
10// 2
11// 3
12// 4
13// Found 5! Stopping loop.
4

Use `continue` to skip an iteration

The continue keyword skips the rest of the current loop's code and moves to the next repetition.

javascript
1for (let i = 1; i <= 5; i++) {
2 if (i === 3) {
3 console.log('Skipping 3.');
4 continue; // Skip the rest of this loop cycle for i=3
5 }
6 console.log(i);
7}
8// Output:
9// 1
10// 2
11// Skipping 3.
12// 4
13// 5

Avoid very long running loops in the browser

If a loop takes too long to finish, it can make a web page unresponsive. The browser might even show a 'script not responding' warning. For very large datasets, consider breaking work into smaller pieces or using web workers.

Loop Statement Reference

Loop Statement Reference

Loop TypeSyntax ExampleWhen to UseKey Feature
`for``for (let i=0; i<5; i++) { ... }`When you know the exact number of repetitions.Has built-in counter control.
`while``while (condition) { ... }`When the number of repetitions is unknown, based on a condition.Checks condition before each run.
`do...while``do { ... } while (condition);`When you need to run the loop body at least once.Runs once, then checks condition.
`for...of` (for arrays)`for (const item of array) { ... }`Easily iterate over items in an array or other iterable objects.Directly gets each item's value.

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which loop is best when you know exactly how many times you need to repeat an action?

Quick Check

What will be the final value of x after this code runs? let x = 0; while (x < 3) { x = x + 1; }

Quick Check

What keyword stops a loop completely and moves to the code after the loop?

Quick Check

When does a do...while loop check its condition?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Loops — automate repetitive tasks by running code blocks multiple times.
  • 2for loop — best for known number of repetitions (e.g., counting from 0 to 10).
  • 3while loop — best for unknown repetitions, runs as long as a condition is true.
  • 4do...while loop — similar to while, but guarantees the code runs at least once.
  • 5Loop partsfor loops have initialization, condition, and increment/decrement.
  • 6Infinite loop — occurs if a loop's condition never becomes false; can crash programs.
  • 7break keyword — immediately stops the entire loop.
  • 8continue keyword — skips the current loop iteration and moves to the next.
  • 9for...of — a modern loop for easily iterating over items in arrays and other collections.
  • 10Nested loops — placing one loop inside another, useful for grids or complex data.

Arrays

Learn how to store lists of data, which are often processed using loops.

Conditional Statements

Understand if/else statements for making decisions inside or outside loops.

Functions

See how to wrap loop logic into reusable functions for cleaner code.

Objects

Explore how to loop through properties of objects using different methods.

You've Mastered Loop Statements!

You now understand how to use for, while, and do...while loops to repeat actions in your JavaScript code. You can also use break and continue to control loop behavior. Loops are a powerful tool for automating tasks and processing data.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning