The Most Common Choice

The for loop is the " Swiss Army knife " . It's a bit more complex to write, but allows you to keep all the loop control logic on a single line.

1. Loop Anatomy

for (let i = 0; i < 3; i++) { 
  alert(i); 
}
  1. Begin (let i = 0): Executes once upon entering.
  2. Condition (i < 3): Checked before every iteration. If false — exit.
  3. Body (alert(i)): The code inside runs as long as the condition is true.
  4. Step (i++): Executes AFTER the body, then we go back to step 2.

2. Scope

The variable i declared inside for is visible only inside that loop. This is very convenient because you can use i in different loops on the same page without conflicts.

Tip

Any part of the for loop can be omitted. For example, an infinite loop using for looks like this: for (;;) { ... }.

Important

You can use an existing variable: let i = 0; for (i = 0; i < 3; i++) { ... }. In this case, it will be available even after the loop.