For Loops
👨💼 Great work! You can now control exactly how many times code runs.
🦉 Common for loop patterns:
// Loop through an array by index
const items = ['a', 'b', 'c']
for (let i = 0; i < items.length; i++) {
console.log(i, items[i])
}
// Loop backwards
for (let i = items.length - 1; i >= 0; i--) {
console.log(items[i])
}
// Loop with a step
for (let i = 0; i < 100; i += 10) {
console.log(i) // 0, 10, 20, ...
}
Be careful with your loop condition!
i <= 5 includes 5, while i < 5 stops at
4. Off-by-one errors are one of the most common bugs in programming.