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.
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 toofor(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.
Note Iterates over enumerable string properties, including inherited ones. Avoid for arrays (use for...of). Use Object.hasOwn() to filter inherited keys.
total =0
prices =[12.50,8.99,24.00]for price in prices:
total += price
print(f"Total: ${total:.2f}")for i inrange(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.