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.
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 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.