For Loops in JavaScript

Introduction

for loops repeat code a known number of times or walk across sequences. You will use classic for, for...of, and for...in (with care). Loops power tables, batch processing, and array workflows in real apps.

Prerequisites

Classic for Loop

javascript
// Print 1 through 5
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Structure: for (init; condition; update) { body }

  • init: runs once
  • condition: checked before each iteration
  • update: runs after each iteration
javascript
// Multiplication row for 7
const n = 7;
for (let i = 1; i <= 10; i++) {
  console.log(`${n} x ${i} = ${n * i}`);
}

Use let for the counter—var leaks in older styles.

for...of — Iterate Values

Best for arrays and other iterables when you need each value:

javascript
// Loop array values
const languages = ["JavaScript", "Python", "Java"];
 
for (const lang of languages) {
  console.log(lang);
}

Tip

Best Practice

Prefer for...of over manual index loops when you do not need the index.

for...in — Iterate Keys (Objects)

Walks enumerable property keys of an object (and array indices as strings—usually avoid on arrays):

javascript
// Object keys
const settings = { theme: "dark", lang: "en", fontSize: 14 };
 
for (const key in settings) {
  console.log(key, settings[key]);
}

For arrays, use for...of or .forEach, not for...in, unless you have a specific reason.

Looping Arrays by Index

When you need the index (ranking, neighbors):

javascript
// Index + value
const scores = [88, 92, 75];
 
for (let i = 0; i < scores.length; i++) {
  console.log(`#${i + 1}: ${scores[i]}`);
}

Nested Loops

javascript
// Simple 3x3 grid coordinates
for (let row = 0; row < 3; row++) {
  for (let col = 0; col < 3; col++) {
    console.log(`(${row}, ${col})`);
  }
}

Watch performance—deep nesting on large data can be slow.

Mini Example: Sum Scores

javascript
// Sum numbers in an array
const scores = [90, 85, 88, 92];
let total = 0;
 
for (const score of scores) {
  total += score;
}
 
const average = total / scores.length;
console.log(`Total: ${total}, Average: ${average.toFixed(1)}`);

FAQ

for...of vs for...in?

for...of → values in iterables. for...in → keys on objects. Do not confuse them on arrays.

Can I use const in for...of?

Yes—const item is idiomatic when you do not reassign the binding each iteration.

Is for (;;) infinite loop?

Yes—avoid unless you break intentionally (servers, games). Prefer clear conditions.

What comes next?

While loops and break / continue.