For Loops

A for loop in JavaScript is a control structure used to repeat a block of code a specific number of times. It is commonly used to iterate over arrays or execute code multiple times with a counter.

Illustration of for_loops
Illustration of for_loops

💡 Basic Syntax

for (initialization; condition; update) {
    // code to execute
}

Explanation of the parts:

  • Initialization: Sets up a counter variable (runs once at the start).
  • Condition: A boolean expression checked before each iteration; the loop runs while true.
  • Update: Changes the counter after each iteration (usually increment or decrement).
For Loop Components
PartPurpose
InitializationSet starting point (e.g., let i = 0)
ConditionLoop continues if true (e.g., i < 5)
UpdateChange counter (e.g., i++)

📌 Deep Dive: Counting with a For Loop

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

The loop above starts i at 0, runs while i < 5, and increments i by 1 each time, printing numbers 0 through 4.

💡 Common Uses

  • Iterating over arrays using an index.
  • Repeating tasks a fixed number of times.

📌 Deep Dive: Loop through an Array

JAVASCRIPT
const fruits = ['apple', 'banana', 'cherry'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
Output
apple
banana
cherry

⚠️ Avoid Infinite Loops

If the condition never becomes false, the loop runs forever and can crash your program. Always ensure the update changes the condition eventually.

For example, this loop will never end because i is never updated:

📌 Deep Dive: Infinite Loop Example (Avoid!)

JAVASCRIPT
for (let i = 0; i < 5;) {
  console.log(i);
  // Missing i++ update — infinite loop!
}

💡 Alternative: Looping Backwards

You can count downwards by initializing with a higher number and decrementing:

📌 Deep Dive: Counting Down

JAVASCRIPT
for (let i = 5; i > 0; i--) {
  console.log(i);
}
Output
5
4
3
2
1

💡 Summary

  • For loops repeat code a known number of times.
  • They consist of initialization, condition, and update expressions.
  • Commonly used for array iteration or counting.
  • Beware of infinite loops by ensuring the condition will eventually be false.