For loop

4 snippets across 2 stacks — JavaScript, Python

Also written as for in loop · for of loop

JSJavaScript

for Loop

JS · Control Flow
syntax
for (init; condition; update) { ... }
example
const items = ["apple", "banana", "cherry"];
for (let i = 0; i < items.length; i++) {
  console.log(`${i + 1}. ${items[i]}`);
}
output
"1. apple"
"2. banana"
"3. cherry"

Note Classic loop when you need the index. For simple iteration, prefer for...of. Cache .length in the initializer if the array is very large and not changing.

for...of Loop

JS · Control Flow
syntax
for (const element of iterable) { ... }
example
const scores = [88, 92, 75, 100];
let sum = 0;
for (const score of scores) {
  sum += score;
}
console.log(`Average: ${sum / scores.length}`);

// Works with strings too
for (const char of "hello") {
  process(char);
}
output
"Average: 88.75"

Note Works on any iterable: arrays, strings, Maps, Sets, generators. Does NOT work on plain objects -- use Object.entries() or for...in for those.

for...in Loop

JS · Control Flow
syntax
for (const key in object) { ... }
example
const theme = { primary: "#3498db", secondary: "#2ecc71", accent: "#e74c3c" };
for (const colorName in theme) {
  console.log(`${colorName}: ${theme[colorName]}`);
}
output
"primary: #3498db"
"secondary: #2ecc71"
"accent: #e74c3c"

Note Iterates over enumerable string properties, including inherited ones. Avoid for arrays (use for...of). Use Object.hasOwn() to filter inherited keys.

PYPython

for Loops

PY · Control Flow
syntax
for item in iterable:
    ...
example
total = 0
prices = [12.50, 8.99, 24.00]
for price in prices:
    total += price
print(f"Total: ${total:.2f}")

for i in range(3):
    print(f"Attempt {i + 1}")
output
Total: $45.49
Attempt 1
Attempt 2
Attempt 3

Note range(n) produces 0 through n-1. Use range(start, stop, step) for more control. Python for loops iterate over any iterable, not just numeric ranges.