Loops in JS (For Loop)
The Power of Repetition
Imagine you need to print "Hello Himubey!" to the console 100 times. Writing console.log("Hello Himubey!"); one hundred times would be a nightmare.
In programming, Loops allow you to execute a block of code repeatedly as long as a certain condition remains true.
The for Loop
The for loop is the most common loop in JavaScript. It is perfect when you know exactly how many times you want the loop to run.
Syntax Structure:
for (initialization; condition; increment/decrement) {
// code to run
}
Example:
for (let i = 1; i <= 5; i++) {
console.log("Iteration number: " + i);
}
How it works step-by-step:
- Initialization (
let i = 1): Runs only ONCE at the very beginning. Creates a counter variablei. - Condition (
i <= 5): Checked before every single loop iteration. If true, the loop runs. If false, the loop completely stops. - Execution: The code inside the
{}runs (console.log). - Increment (
i++): Runs after the code execution. Increasesiby 1 (soibecomes 2). - The cycle repeats from step 2 until the condition is false.
Loops are essential for tasks like displaying lists of products, processing arrays of data, or rendering multiple UI components dynamically!
💡 Himanshu's Tip:
When writing for loops, you'll almost always see developers use let i = 0;. We start counting from 0 (not 1) in programming because Arrays and Lists are 'zero-indexed'. Get used to starting at zero!
Interview Questions
- What are the three optional expressions in a
forloop declaration? - What happens if you forget to include an increment/decrement condition in your loop?
- Why do we typically initialize loop counters at 0 instead of 1?