Skip to content

JavaScript Tutorial Loops

JavaScript for Loop

Lesson 46 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

A loop repeats code. The for loop is the one to use when you know how many times to repeat.

script.js
JS
for (let i = 0; i < 5; i++) {
  console.log("Round", i);
}

The loop has three parts inside the parentheses, separated by semicolons:

  1. Start: let i = 0 runs once before the loop.
  2. Condition: i < 5 is checked before every round. When it is false, the loop ends.
  3. Update: i++ runs after every round.

So the loop runs for i = 0, 1, 2, 3 and 4: five times.

Looping over an array

Array positions start at 0, and the last position is length - 1.

script.js
JS
const fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}

Counting down and stepping

script.js
JS
for (let i = 3; i > 0; i--) {
  console.log(i); // 3, 2, 1
}
console.log("Liftoff!");

for (let i = 0; i <= 10; i += 5) {
  console.log(i); // 0, 5, 10
}

Building something

script.js
JS
let sum = 0;
for (let i = 1; i <= 5; i++) {
  sum += i;
}
console.log(sum); // → 15

Mistakes to watch for

  • Off by one: i <= fruits.length runs one time too many and reads undefined. Use < with length.
  • Infinite loops: forgetting the update (i++) means the condition never becomes false and the page freezes. If that happens, close the tab.
  • Modifying the array while looping can skip items.

Do you need a for loop?

For arrays, for...of (next chapters) and methods like map and filter are often clearer. The classic for loop is still the right tool when you need the index, count with steps, or loop backwards. See Which Loop Should You Use?.