JavaScript•Loops
JavaScript For Loops, for...of, and for...in Iteration
Compare classical counting loops against modern ES6 for...of iteration over arrays, strings, and sets.
Syntax
for (let i = 0; i < n; i++) {}
for (const item of array) {}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| for...of | Loop Statement | Iterates over values of iterable collections (arrays, strings). |
| for...in | Loop Statement | Iterates over enumerable keys of an object. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// 1. Classical for loop
console.log("--- Multiples of 3 ---");
for (let i = 1; i <= 4; i++) {
console.log(i + " * 3 =", i * 3);
}
// 2. Modern for...of loop over arrays
console.log("\n--- Technologies ---");
const stack = ["Node.js", "TypeScript", "React"];
for (const tech of stack) {
console.log("-> " + tech);
}Expected Output:
--- Multiples of 3 --- 1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 4 * 3 = 12 --- Technologies --- -> Node.js -> TypeScript -> React
How It Works: Step-by-Step
- Lines 3-5: Standard loop with initializer, condition, and increment expression.
- Lines 10-12: for...of extracts array elements directly without indexing.
Key Concepts
- for...of iterates over values of an array or iterable.
- for...in iterates over keys/properties of an object.
- Prefer for...of or Array.prototype.forEach/map for cleaner, declarative code.
Common Mistake: Using for...in on an array expecting values instead of index strings
for...in iterates over indices as strings ("0", "1"), which causes concatenation bugs.
❌ Incorrect
for (const x in [10, 20]) { console.log(x + 1); } // Prints "01", "11"!✅ Correct
for (const x of [10, 20]) { console.log(x + 1); } // Prints 11, 21Related JavaScript Tutorials & Compiler
JavaScript While and Do...While Loops with Examples
Execute code repeatedly while a specified condition evaluates to true.
JavaScript Break and Continue Statements in Loops
Interrupt or skip loop iterations with break and continue statements.
JavaScript Arrays: Methods (map, filter, reduce, slice)
Master modern array manipulation using push, pop, slice, map, filter, and reduce.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.