JavaScript For Loop
A `for` loop repeats a block of code a specific number of times, defined by three parts: initialization, condition, and increment/decrement.
For loops are ideal when you know in advance how many times you need to repeat something, such as iterating over an array by index.
Anatomy of a for loop
`for (let i = 0; i < 5; i++) { ... }` initializes i to 0, runs while i < 5, and increments i after each iteration.
Looping over arrays
`for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }` is the classic index-based way to visit every array element.
for (let i = 0; i < 5; i++) {
console.log(i);
}0
1
2
3
4The loop runs 5 times, with i taking values 0 through 4.
let arr = ["a", "b", "c"];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}a
b
cIndexing with i lets us visit every array element in order.
Key points
- A for loop has initialization, condition, and increment parts.
- It runs until the condition becomes false.
- Commonly used to iterate over arrays by index.
- Infinite loops occur if the condition never becomes false.
