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.
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:
console.log(i);
}
let i = 0.true, the body runs. If false, the loop stops immediately.
// 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 hilet (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 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:
// ── 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]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.
// ── 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 9break & 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:
i++), then re-checks the condition.break label or
continue label to target an outer loop from inside a nested one.
// ── 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 hereCommon 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 |
// ── 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.
Common Patterns & Recipes
These are the everyday loop utilities you'll reach for constantly in real JavaScript projects:
// ── 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
}for (let i = 0; i < 5; i++)
continue do inside a For Loop?- 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— nevervar— 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.
breakexits the entire loop immediately;continueskips to the update step.- Use labelled loops (
outer: for ...) tobreakorcontinuean 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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.