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:
- The Start:
let i = 0 - The Condition:
i < 10(Keep going as long as this is true) - 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
- Infinite Loops: If your condition
i < 10is always true (e.g., you forgot to doi++), your browser will freeze and potentially crash your computer. Always check your exit condition. - Off-By-One Errors: Logic errors where the loop runs one time too many or too few (e.g., using
<=instead of<). - 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
- The Countdown: Write a for-loop that counts DOWN from 10 to 1 and then prints "Blastoff!"
- The Even Stevens: Write a loop that prints only even numbers between 1 and 20.
- The Summer: Create an array of numbers and use a
for...ofloop to calculate the total sum.