









For Loop in JavaScript
Syntax, Variations, and Examples
Understanding the For Loop in JavaScript
The for loop in JavaScript is a fundamental building block that allows you to run a block of code multiple times. It's like telling the browser, “Do this task again and again — but under my conditions.” Whether you're processing arrays, printing numbers, or building logic for games, the for
loop is your go-to structure.
Basic Syntax of a For Loop
for (initialization; condition; increment) {
// code block to be executed
}
Explanation of each part:
initialization
– typically used to set a counter variable.condition
– defines how long the loop should run.increment
– updates the counter each time the loop runs.
Example 1: Print Numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
1
2
3
4
5
How This Works
The loop starts with i = 1
, checks if i <= 5
, then executes the console.log(i)
. After that, i
increases by 1. This continues until the condition is false.
Example 2: Sum of First N Numbers
let n = 5;
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
console.log("Sum:", sum);
Sum: 15
For Loop with Arrays
Looping through arrays is where the for
loop becomes essential.
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
apple
banana
cherry
Example 3: Print Even Numbers from 1 to 10
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
2
4
6
8
10
Nested For Loops
What if you need to loop within a loop? That’s where nested for
loops come in.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 2; j++) {
console.log(`i = ${i}, j = ${j}`);
}
}
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
Reverse Looping
You can also run the loop backward:
for (let i = 5; i >= 1; i--) {
console.log(i);
}
5
4
3
2
1
Break and Continue in For Loops
Break Statement
Stops the loop when a certain condition is met.
for (let i = 1; i <= 10; i++) {
if (i === 6) break;
console.log(i);
}
1
2
3
4
5
Continue Statement
Skips the current iteration and continues with the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
1
2
4
5
Real-World Example: Create Multiplication Table
let number = 4;
for (let i = 1; i <= 10; i++) {
console.log(`${number} x ${i} = ${number * i}`);
}
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
...
4 x 10 = 40
Tips & Best Practices
- Use
let
orconst
instead ofvar
to declare loop counters. - When working with arrays, prefer
for...of
orforEach()
if mutation or index isn’t needed. - Avoid deeply nested loops if possible — they affect performance and readability.
Summary
The for
loop is a powerhouse in JavaScript — compact, flexible, and indispensable. From printing simple sequences to handling complex nested structures, it gives you direct control over the flow. Understanding its syntax and behavior is key to writing clean and efficient code.
Comments
Loading comments...