Table of Content
JavaScript runs code in different ways, but the for loop stays one of the most common tools. You use it to repeat the same task many times.
Also, you can count numbers, move through arrays, or repeat steps with small changes. You decide when the loop starts, when it stops, and how it moves.
In this article, you will cover how for loop works in JavaScript with examples.
What Is the for Loop in JavaScript?
The for loop repeats a block of code a set number of times. You decide where it starts and when it stops. Also how it moves.

A for loop has three main parts inside the parentheses:
- The start
- Condition
- The step.
Here is the syntax:
for (start; condition; step) {
// code runs here
}Each part controls something:
1- What runs once at the start?
This sets the start. The code runs one time before the loop begins.
for (let i = 0; i < 5; i++) {
console.log(i);
}let i = 0; runs once before the loop begins.
2- What runs before each loop?
This checks if the loop should keep going. If false, the loop stops.
for (let i = 0; i < 3; i++) {
console.log(i);
}i < 3 runs before each round.
3- What runs after each loop?
This updates the variable after each round.
for (let i = 0; i < 3; i++) {
console.log(i);
}i++ runs after each time the loop body runs.
Optional Parts of a for Loop
You can leave out parts of a for loop. The loop still runs if the syntax stays valid.
Skip the init part:
You can set the variable outside the loop.
let i = 0;
for (; i < 3; i++) {
console.log(i);
}Skip the condition:
The loop runs forever unless you break it inside.
for (let i = 0;; i++) {
if (i === 3) break;
console.log(i);
}Skip the final expression:
You can update the variable inside the loop body.
for (let i = 0; i < 3;) {
console.log(i);
i++;
}The Common for Loop Uses
The for loop works well when you know how many times you want to repeat something. Here are a few common ways people use it.
- Count from one number to another
- Loop through an array by index
- Loop backward
- Skip by more than one
- Nested loops
Let’s see an example for each one.
You can go through each item using its position:
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}You can count down instead of up.
for (let i = 3; i > 0; i--) {
console.log(i);
}You can step by two or more:
for (let i = 0; i <= 10; i += 2) {
console.log(i);
}You can place a for loop inside another to work with grids or pairs.
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 2; j++) {
console.log(i, j);
}
}Iterating Over Arrays
The for loop gives you full control when you need to go through each item in an array. You can use the index to read, update, or skip items.
Update array items by using their index:
let numbers = [1, 2, 3];
for (let i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2;
}
console.log(numbers); // [2, 4, 6]Start at the index 0 and stop before the length:
let colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}Loop Scope and Multiple Variables
You can set and update more than one variable by using commas.
for (let i = 0, j = 5; i < j; i++, j--) {
console.log(i, j);
}This is useful when you loop from both ends toward the middle or track two values at once.
Each keyword handles scope differently inside a loop:
letcreates a block-scoped variable. Each loop cycle gets its own copy.varcreates a function-scoped variable. It can leak outside the loop.constworks in a loop only if you do not change the variable. You can use it in the loop setup, but not in the update.
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log("let:", i), 0);
}
for (var j = 0; j < 3; j++) {
setTimeout(() => console.log("var:", j), 0);
}Output:
let: 0
let: 1
let: 2
var: 3
var: 3
var: 3let keeps each value. var shares one value across all calls.
The for Loop Without a Body
You can write a for loop that does not use a block of code. This works when all the logic fits inside the loop line.
For example:
let sum = 0;
for (let i = 1; i <= 100; sum += i++);
console.log(sum);The loop adds numbers to sum. It does everything in the for line, and skips the loop body.
This style can look odd, so use it only when the loop stays simple and easy to read.
Mistakes to Avoid
These bugs can break your for loop or cause hard-to-find errors. Watch for them when you write loops.
- Using
varinstead oflet - Off-by-one errors
- Infinite loops
- Changing array length during the loop
Here are examples:
var does not have block scope. It can cause wrong values in async code.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Prints: 3, 3, 3 (not 0, 1, 2)Use let to keep the value scoped to each loop step.
You might run the loop one time too many or too few.
let nums = [10, 20, 30];
// Wrong: i <= nums.length
for (let i = 0; i <= nums.length; i++) {
console.log(nums[i]); // Last one is undefined
}Check your loop condition. i < nums.length is correct.
If the condition never becomes false, the loop never stops.
for (let i = 0; i >= 0; i++) {
// This keeps going forever
}Always make sure the loop can end.
If you add or remove items while looping, indexes shift and break the logic.
let items = [1, 2, 3, 4];
for (let i = 0; i < items.length; i++) {
items.pop();
}
console.log(items); // Only [1, 2] remainsIf you must change the array, use a copy or loop backward.
The break and continue Statements
You can control how a for loop runs by using break to stop it or continue to skip to the next step.
Use break when you want to exit the loop before it ends.
for (let i = 0; i < 10; i++) {
if (i === 3) break;
console.log(i);
}
// Output: 0, 1, 2The loop stops when i hits 3.
Use continue when you want to skip part of the loop and move to the next round.
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i);
}
// Output: 0, 1, 3, 4The loop skips over 2 and keeps going.
for vs while, for...of, and for...in
You use the for loop when you know the number of times to repeat a task. It sets a counter at the start and checks a stop condition. It also updates the counter after each cycle.
The while loop runs as long as the condition stays true. It checks the condition before each run.
The for...of loop steps through the values in arrays, strings, or other collections. It gives you the value of each item, not the index.
The for...in loop moves through the keys of an object. It gives you the property names, not the values.
Here is a table that compares each one.
| Loop Type | Use Case | Iterates Over | Example Code |
|---|---|---|---|
for | When the number of iterations is known. | A range of numbers or indices. | for (let i = 0; i < 5; i++) { console.log(i); } |
while | When the number of iterations is not known. | Condition-based. | let i = 0; while (i < 5) { console.log(i); i++; } |
for...of | When iterating over values of iterable objects (arrays, strings, etc.). | Values of an iterable (array, string, etc.). | for (let value of arr) { console.log(value); } |
for...in | When iterating over keys (properties) of an object. | Keys (properties) of an object. | for (let key in person) { console.log(key, person[key]); } |
Examples of JavaScript for Loop
This example uses multiple variables inside the for loop to handle two different counters at the same time.
for (let i = 0, j = 10; i < 5; i++, j -= 2) {
console.log(`i: ${i}, j: ${j}`);
}Output:
i: 0, j: 10
i: 1, j: 8
i: 2, j: 6
i: 3, j: 4
i: 4, j: 2
Here, i starts at 0 and increases by 1, while j starts at 10 and decreases by 2.
In some cases, you may need to use a for loop inside another for loop, such as when working with multi-dimensional arrays or tables.
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1
i: 1, j: 2
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
You can also use a for loop to iterate backwards by adjusting the condition and decrementing the counter.
for (let i = 5; i >= 0; i--) {
console.log(i);
}Output:
5
4
3
2
1
0
Sometimes, you may want to skip certain iterations within a loop. The continue statement allows you to do that.
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
console.log(i);
}Output:
0
1
2
4
If you need to stop a loop prematurely, you can use the break statement.
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i);
}Output:
0
1
2
Wrapping Up
You learned how to use the for loop in JavaScript to repeat tasks a set number of times. You saw how to control the loop with expressions and avoid common mistakes.
Here is a quick recap:
- The
forloop works well when you know how many times to repeat a task. You control the start, the stop point, and the step. - You can leave out parts of the loop setup, like the start value, the condition, or the update step.
- You can use more than one variable in the loop. You can update them in each cycle and control their scope with
let,var, orconst. - You also saw how to stop mistakes like off-by-one errors or endless loops. You can use
breakandcontinueto manage what the loop does.
FAQ’s
What is a for loop in JavaScript?
for (let i = 0; i < 5; i++) {
console.log(i);
}
How does a for loop work in JavaScript?
- Initialization: Runs once before the loop starts.
- Condition: Checked before each iteration. If it evaluates to false, the loop stops.
- Step: Runs after each iteration, updating variables that control the loop.
for (let i = 0; i < 3; i++) {
console.log(i); // Outputs 0, 1, 2
}
What are the optional parts of a for loop?
- Skip initialization: You can set the variable outside the loop.
- Skip condition: The loop will run forever unless you break it inside.
- Skip step: You can update the counter inside the loop body.
let i = 0;
for (; i < 3; i++) {
console.log(i);
}
What is the difference between for, while, for...of, and for...in loops?
- for loop: Used when you know how many times you want to loop.
- while loop: Used when the number of iterations is unknown; checks the condition before each iteration.
- for...of loop: Iterates over the values of an iterable object like an array or string.
- for...in loop: Iterates over the keys (or properties) of an object.
// for loop
for (let i = 0; i < 3; i++) { console.log(i); }
// for...of loop
let arr = [1, 2, 3];
for (let value of arr) { console.log(value); }
// for...in loop
let person = { name: "John", age: 30 };
for (let key in person) { console.log(key, person[key]); }
How can I skip or stop a for loop early?
- break: Exits the loop completely.
- continue: Skips the current iteration and moves to the next one.
// Break the loop
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // Output: 0, 1, 2
}
// Continue to the next iteration
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
console.log(i); // Output: 0, 1, 2, 4
}
Similar Reads
JavaScript removes unused memory blocks with garbage collection. It frees memory space so programs run without leaks. What is JavaScript…
You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of…
You need to compare values in almost every JavaScript program. This is where comparison operators come in. They check if…
JavaScript Math.log() was added to help people find the natural log of a number. It solves real problems in science…
You will learn what the JavaScript valueOf function does and how it works. It returns the primitive value of an…
JavaScript code follows some rules that help both new and old developers. A project without rules in code creates trouble…
Object constructors and class constructors in JavaScript create objects in a structured way. Both provide methods to build reusable code.…
Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…
In this guide, you will learn how JavaScript functions work and why they matter. Each section shows what you need…
JavaScript Symbol Type gives a way to make unique values. A Symbol never matches any other value and this helps…