Ch 19 / 78
Chapter 19 Beginner 7 min read JavaScript

For Loop

The for loop is the most-used loop in JavaScript. It packs initialization, condition, and update into a single line — giving you precise control over iteration count, direction, and step size.

What you'll learn
The three parts of a For Loop — init, condition, update
Counting up, counting down, and custom step sizes
Looping over arrays and strings by index
Nested For Loops and multi-dimensional patterns
break and continue inside a For Loop
Common pitfalls — infinite loops and off-by-one errors

For Loop Syntax & Anatomy

A for loop repeats a block of code a specific number of times. All three control expressions sit inside the parentheses, separated by semicolons:

for (let i = 0; i < 5; i++) {
  console.log(i);
}
Initialization — runs once before loop starts Condition — checked before every iteration Update — runs after every iteration Body — code that repeats
let i = 0
Initialization
Runs once before the first iteration. Declares and sets the loop counter. Usually let i = 0.
i < 5
Condition
Evaluated before each iteration. If true, the body runs. If false, the loop stops immediately.
i++
Update
Runs after each iteration, before the next condition check. Changes the counter — usually increments or decrements it.
{ ... }
Loop Body
The block of code that executes each time the condition is true. Can be one line (no braces) or a full block.
JavaScript — Basic For Loop
// Print 0 through 4
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0 1 2 3 4

// Execution order on each iteration:
// 1. Check condition (i < 5)
// 2. Run body if true
// 3. Run update (i++)
// 4. Repeat from step 1

// Single-line body (braces optional for one statement)
for (let i = 0; i < 3; i++) console.log("hi");
// hi hi hi
Note
Always use let (not var) for the loop variable. Using var leaks the counter into the outer scope, which causes subtle bugs — especially inside closures and async code.

Counting Up, Down & Custom Steps

The update expression isn't limited to i++. You can count in any direction or skip values using any numeric expression:

Count Up
Start at 0 (or any value), increment by 1 each iteration.
i = 0; i < n; i++
Count Down
Start at the last index, decrement toward 0. Useful for reversals.
i = n-1; i >= 0; i--
Step by 2
Skip every other value. Great for even/odd processing.
i = 0; i < n; i += 2
Custom Range
Start and end at any arbitrary values, with any step size.
i = 10; i <= 100; i += 10
JavaScript — Loop Variations
// ── Count up from 1 to 5 ────────────────────────────────────
for (let i = 1; i <= 5; i++) {
console.log(i); // 1 2 3 4 5
}

// ── Count down from 5 to 1 ───────────────────────────────────
for (let i = 5; i >= 1; i--) {
console.log(i); // 5 4 3 2 1
}

// ── Even numbers 0–10 (step by 2) ────────────────────────────
for (let i = 0; i <= 10; i += 2) {
console.log(i); // 0 2 4 6 8 10
}

// ── Multiples of 10 from 10 to 100 ───────────────────────────
for (let i = 10; i <= 100; i += 10) {
process.stdout.write(i + " "); // 10 20 30 40 50 60 70 80 90 100
}

// ── Reverse through an array ─────────────────────────────────
const fruits = ["apple", "banana", "cherry"];
for (let i = fruits.length - 1; i >= 0; i--) {
console.log(fruits[i]); // cherry → banana → apple
}

Looping Over Arrays & Strings

One of the most common uses of a for loop is iterating over an array or string by index. Use array.length as the condition to always match the array's actual size:

JavaScript — Arrays & Strings
// ── Looping an array ─────────────────────────────────────────
const scores = [85, 92, 78, 96, 61];

for (let i = 0; i < scores.length; i++) {
console.log(`Score ${i + 1}: ${scores[i]}`);
}
// Score 1: 85 | Score 2: 92 | ...

// ── Sum all values ───────────────────────────────────────────
let total = 0;
for (let i = 0; i < scores.length; i++) {
total += scores[i];
}
console.log("Total:", total); // 412
console.log("Average:", total / scores.length); // 82.4

// ── Looping a string ─────────────────────────────────────────
const word = "Hello";
for (let i = 0; i < word.length; i++) {
console.log(`[${i}] → ${word[i]}`);
}
// [0] → H [1] → e [2] → l [3] → l [4] → o

// ── Build a new array with transformation ────────────────────
const doubled = [];
for (let i = 0; i < scores.length; i++) {
doubled.push(scores[i] * 2);
}
console.log(doubled); // [170, 184, 156, 192, 122]
Tip
Cache array.length in a variable before the loop if the array is large and you're not changing it: for (let i = 0, len = arr.length; i < len; i++). This avoids re-evaluating the property on every iteration — a micro-optimisation worth knowing for performance-critical code.

Nested For Loops

You can place a for loop inside another loop. The inner loop runs completely for every single iteration of the outer loop. Common uses: 2D grids, multiplication tables, and matrix operations.

Outer loop: i = 0 → runs inner loop fully Inner loop: j = 0, 1, 2 → body runs 3× → (0,0) (0,1) (0,2) Outer loop: i = 1 → runs inner loop fully Inner loop: j = 0, 1, 2 → body runs 3× → (1,0) (1,1) (1,2) Outer loop: i = 2 → runs inner loop fully Inner loop: j = 0, 1, 2 → body runs 3× → (2,0) (2,1) (2,2)
JavaScript — Nested Loops
// ── Multiplication table (3×3) ───────────────────────────────
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} × ${j} = ${i * j}`);
}
}
// 1×1=1 1×2=2 1×3=3
// 2×1=2 2×2=4 2×3=6
// 3×1=3 3×2=6 3×3=9

// ── Star pattern (triangle) ──────────────────────────────────
let pattern = "";
for (let row = 1; row <= 5; row++) {
for (let col = 1; col <= row; col++) {
pattern += "★ ";
}
pattern += "\n";
}
console.log(pattern);
// ★
// ★ ★
// ★ ★ ★
// ★ ★ ★ ★
// ★ ★ ★ ★ ★

// ── 2D array (matrix) ────────────────────────────────────────
const matrix = [[1,2,3], [4,5,6], [7,8,9]];
for (let r = 0; r < matrix.length; r++) {
for (let c = 0; c < matrix[r].length; c++) {
process.stdout.write(matrix[r][c] + " ");
}
console.log();
}
// 1 2 3
// 4 5 6
// 7 8 9

break & continue in a For Loop

break exits the loop entirely. continue skips the rest of the current iteration and jumps straight to the update step. Both are critical for writing efficient loops:

break
Immediately exits the entire loop. Execution continues with the statement after the closing brace. Useful for early-exit searches.
continue
Skips the remaining body of the current iteration and jumps to the update expression (i++), then re-checks the condition.
label: for (...)
Named loops allow break label or continue label to target an outer loop from inside a nested one.
JavaScript — break & continue
// ── break — stop as soon as 7 is found ───────────────────────
const nums = [2, 5, 7, 9, 11];
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 7) {
console.log(`Found 7 at index ${i}`);
break; // exits loop — 9 and 11 are never checked
}
}

// ── continue — skip odd numbers ──────────────────────────────
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) continue; // skip odd → jump to i++
console.log(i); // prints 2 4 6 8 10
}

// ── Labelled break — exit outer loop from inner ──────────────
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer; // exits BOTH loops
console.log(i, j);
}
}
// 0 0 | 0 1 | 0 2 | 1 0 ← stops here
⚡
Free Resource
Download our JavaScript Cheat Sheet
Loops, control flow & iteration patterns — all on one page.
Get Sheet

Common Mistakes & Pitfalls

The for loop has a few classic gotchas. Learn them once and you'll avoid them forever:

Mistake What Goes Wrong Fix
Infinite loop Condition never becomes false — browser/tab freezes Ensure update expression brings counter toward the failing condition
Off-by-one i <= arr.length reads one past the end → undefined Use i < arr.length (strict less-than) for arrays
Using var in loops Counter leaks to outer scope; closures capture wrong value Always declare counter with let
Mutating array mid-loop Adding/removing items changes .length, skipping or repeating items Cache length before loop or iterate a copy
Semicolon after for (...) for (...) ; creates an empty loop body — code below runs once Never put a bare ; directly after the closing parenthesis
Skipping braces on multiline body Only the first statement is in the loop; rest runs after loop ends Always use { } for multi-statement bodies
JavaScript — Mistakes vs Fixes
// ── Off-by-one — accessing arr[arr.length] → undefined ───────
const arr = ["a", "b", "c"];
// ❌ Wrong — i <= arr.length reads index 3 (undefined)
for (let i = 0; i <= arr.length; i++) console.log(arr[i]);

// ✅ Correct — strict <
for (let i = 0; i < arr.length; i++) console.log(arr[i]);

// ── Infinite loop — forgot to increment ──────────────────────
// ❌ Never do this — hangs the browser
// for (let i = 0; i < 5; ) { console.log(i); }

// ✅ Always increment
for (let i = 0; i < 5; i++) console.log(i);

// ── var vs let in loops ───────────────────────────────────────
// ❌ var leaks — all callbacks see i = 3 (final value)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 3 3 3
}

// ✅ let creates a new binding per iteration
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0 1 2
}

Try It — Live Editor

Experiment with For Loops below. Try changing the bounds, step size, or adding a break/continue condition.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are the everyday loop utilities you'll reach for constantly in real JavaScript projects:

JavaScript — Loop Recipes
// ── Find index of a value ────────────────────────────────────
function indexOf(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}

// ── Reverse an array in place ─────────────────────────────────
function reverse(arr) {
for (let i = 0, j = arr.length - 1; i < j; i++, j--) {
[arr[i], arr[j]] = [arr[j], arr[i]]; // swap
}
return arr;
}
reverse([1, 2, 3, 4, 5]); // [5, 4, 3, 2, 1]

// ── FizzBuzz (classic interview) ─────────────────────────────
for (let i = 1; i <= 20; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}

// ── Two-pointer loop — check palindrome ──────────────────────
function isPalindrome(str) {
for (let i = 0, j = str.length - 1; i < j; i++, j--) {
if (str[i] !== str[j]) return false;
}
return true;
}
isPalindrome("racecar"); // true
isPalindrome("hello"); // false

// ── Multiple counters in one loop ────────────────────────────
for (let i = 0, j = 10; i < j; i++, j--) {
console.log(i, j); // 0,10 → 1,9 → 2,8 → 3,7 → 4,6
}
Quick Check
How many times does this loop run? for (let i = 0; i < 5; i++)
Quick Check
What does continue do inside a For Loop?
Chapter Summary
  • The For Loop syntax is for (init; condition; update) { body } — all three parts are optional but the semicolons are mandatory.
  • The initialization runs once; the condition is checked before each iteration; the update runs after each iteration.
  • Always declare the loop counter with let — never var — to avoid scope leaks and closure bugs.
  • Use i < array.length (strict less-than) to avoid off-by-one errors when iterating arrays.
  • Nested loops multiply iterations — the inner loop runs fully for every single iteration of the outer loop.
  • break exits the entire loop immediately; continue skips to the update step.
  • Use labelled loops (outer: for ...) to break or continue an outer loop from inside a nested one.
  • Common recipes include: array sum, FizzBuzz, two-pointer palindrome check, and star pattern with nested loops.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel