For Loops: The Power of Repetition

For Loops: The Power of Repetition in JavaScript: Computers never get bored. If you need to print "Hello" 1,000,000 times, a human would quit, but a computer…

Concept Explanation

Computers never get bored. If you need to print "Hello" 1,000,000 times, a human would quit, but a computer does it in a fraction of a second using a Loop.

The for loop is the most common. It has a three-step setup:

  1. The Start: let i = 0
  2. The Condition: i < 10 (Keep going as long as this is true)
  3. The Step: i++ (Add 1 after every round)

Syntax or Core Structure

// Basic Loop
for (let i = 0; i < 5; i++) {
    console.log(`Round ${i}`);
}

// Looping through an Array (The Modern Way)
const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
    console.log(fruit);
}

Common Mistakes

  1. Infinite Loops: If your condition i < 10 is always true (e.g., you forgot to do i++), your browser will freeze and potentially crash your computer. Always check your exit condition.
  2. Off-By-One Errors: Logic errors where the loop runs one time too many or too few (e.g., using <= instead of <).
  3. Performance: Don't put heavy work (like talking to a database) inside a loop if you can avoid it. It will slow your app down to a crawl.

Practice Exercises

  1. The Countdown: Write a for-loop that counts DOWN from 10 to 1 and then prints "Blastoff!"
  2. The Even Stevens: Write a loop that prints only even numbers between 1 and 20.
  3. The Summer: Create an array of numbers and use a for...of loop to calculate the total sum.