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.

Frequently asked questions

How does JavaScript handle for loop?
This task is covered in 2 stacks on this page: JavaScript, Python. The "for Loop" snippet in JavaScript uses `for (init; condition; update) { ... }`.
Which code does the JavaScript example use?
The "for Loop" snippet uses `for (init; condition; update) { ... }`, from the Control Flow section of the JavaScript cheat sheet.
Which stacks cover "for loop" on this page?
JavaScript, Python. Together they hold 4 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "for Loop": 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.