JavaScript
For Loop Examples



Understanding the for Loop in JavaScript

The for loop is used to repeat a block of code a known number of times. It's one of the most commonly used loops in programming. The structure includes an initializer, a condition, and an increment/decrement.


// Syntax of a for loop
for (initialization; condition; increment) {
  // code to run
}
    

Example 1: Print numbers from 1 to 5

Let's begin with a simple example. We want to print numbers from 1 to 5 using a for loop.


for (let i = 1; i <= 5; i++) {
  console.log(i);
}
    

Output:

1
2
3
4
5
    

Why does this work?

The loop starts with i = 1. It checks if i <= 5. If true, it runs console.log(i), then increments i by 1. This continues until i becomes 6, where the condition fails.

Question:

What happens if we use i < 5 instead of i <= 5?

Answer: The loop will print 1 to 4 instead of 1 to 5.

Example 2: Sum of first 5 natural numbers

We will use a for loop to calculate the sum of numbers from 1 to 5.


let sum = 0;
for (let i = 1; i <= 5; i++) {
  sum += i;
}
console.log("Sum is:", sum);
    

Output:

Sum is: 15
    

Explanation:

We start with sum = 0 and keep adding i to sum in each loop. Finally, we print the result.

Example 3: Looping through an Array

Let’s use a for loop to print all elements of an array.


let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
    

Output:

Apple
Banana
Mango
    

Why i < fruits.length?

Because arrays are zero-indexed. fruits.length is 3, so valid indices are 0, 1, and 2.

Example 4: Countdown from 5 to 1

Use a for loop in reverse to print numbers from 5 down to 1.


for (let i = 5; i >= 1; i--) {
  console.log(i);
}
    

Output:

5
4
3
2
1
    

Example 5: Print even numbers between 1 and 10

We use the modulus operator % to check if a number is even.


for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    console.log(i);
  }
}
    

Output:

2
4
6
8
10
    

Practice Question:

How would you print only odd numbers between 1 and 10?

Answer: Use i % 2 !== 0 inside the if condition.

Summary

Next Steps

Try writing your own for loops to practice: print multiplication tables, reverse arrays, or sum even numbers.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You 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.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M