JavaScript for Loop: How to Iterate Arrays by Examples

JavaScript for Loop

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.

JavaScript for Loop

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:

  • let creates a block-scoped variable. Each loop cycle gets its own copy.
  • var creates a function-scoped variable. It can leak outside the loop.
  • const works 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: 3

let 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 var instead of let
  • 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] remains

If 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, 2

The 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, 4

The 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 TypeUse CaseIterates OverExample Code
forWhen the number of iterations is known.A range of numbers or indices.for (let i = 0; i < 5; i++) { console.log(i); }
whileWhen the number of iterations is not known.Condition-based.let i = 0; while (i < 5) { console.log(i); i++; }
for...ofWhen 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...inWhen 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 for loop 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, or const.
  • You also saw how to stop mistakes like off-by-one errors or endless loops. You can use break and continue to manage what the loop does.

FAQ’s

What is a for loop in JavaScript?

A for loop in JavaScript is used to repeat a block of code a set number of times. You define three main parts within the parentheses: the initialization (start), the condition (stop), and the step (how to move). The loop continues to run as long as the condition evaluates to true, updating the counter after each iteration. Example:
for (let i = 0; i < 5; i++) {
  console.log(i);
}

How does a for loop work in JavaScript?

A for loop works by running the code block repeatedly based on three key parts:
  • 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 example:
for (let i = 0; i < 3; i++) {
  console.log(i);  // Outputs 0, 1, 2
}

What are the optional parts of a for loop?

In a for loop, you can skip parts of the syntax if necessary:
  • 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.
For example:
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?

You can control the flow of the loop using:
  • 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
}
Previous Article

PHP Elvis Operator: How (?:) Works with Examples

Next Article

Polymorphism in PHP: How It Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.