JavaScript ยท Chapter 31 of 55

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.

Example 1 (javascript)
for (let i = 0; i < 5; i++) {
  console.log(i);
}
Output
0
1
2
3
4

The loop runs 5 times, with i taking values 0 through 4.

Example 2 (javascript)
let arr = ["a", "b", "c"];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
Output
a
b
c

Indexing 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.
๐Ÿ’ก Note: Always double-check your loop's stopping condition to avoid accidentally creating an infinite loop.

๐Ÿ“ Quick Quiz

1. How many parts does a for loop header have?

2. What happens if the condition never becomes false?

3. In `for(let i=0;i<5;i++)`, how many times does the loop body run?