⬅ Previous Topic
JavaScript LoopsNext Topic ⮕
JavaScript While Loop⬅ Previous Topic
JavaScript LoopsNext Topic ⮕
JavaScript While LoopThe 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.
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.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
1
2
3
4
5
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.
let n = 5;
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
console.log("Sum:", sum);
Sum: 15
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
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
2
4
6
8
10
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
You can also run the loop backward:
for (let i = 5; i >= 1; i--) {
console.log(i);
}
5
4
3
2
1
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
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
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
let
or const
instead of var
to declare loop counters.for...of
or forEach()
if mutation or index isn’t needed.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.
⬅ Previous Topic
JavaScript LoopsNext Topic ⮕
JavaScript While LoopYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.