for loop javascript

JavaScript for Loop: How to iterate (with examples)

JavaScript for loop is one of many available loops to repeat any given sequence of code.

Here we will look how we can use the for loop. This tutorial will help you understand for loops from the basics.

What is for loop ?

For loop is the control flow statement. It helps us repeat a block of code specified number of times.

for loop is entry controlled loop, meaning the condition is evaluated before the body is executed.

Let us look at the syntax of for loop.

for (i = 0; i < 10; i++) {
    console.log("learning loops.");
}Code language: JavaScript (javascript)

The above example prints the “learning loops.” 10 times. We will look at other examples below.

Explaining for loop syntax

Let me break down the syntax of for loop. i is the variable and it contains the value 0 initially. So,

  1. i = 0; is the variable declaration
  2. i < 10; is the exit control condition; the loop will continue till i is less than 10.
  3. And, i++; is the increment block.

In the above list, After incrementing the value the loop evaluates the exit condition, and the repetition continues.

But the variable declaration ( i.e. i = 0; ) is done only once.

JavaScript for loop example

Let us look at multiple JavaScript for each loop examples one by one.

Sum of all numbers from 1 to 100

To calculate the sum of all numbers from 1 to 100 we can simply run the code below.

var sum = 0;

for (i = 1; i <= 100; i++) {

    sum = sum + i;


console.log("the sum of numbers from 1 to 100 is : " + sum);Code language: JavaScript (javascript)

The i <= 100 will be true till i‘s value is less than or equal to 100.

Calculating factorial of 12

Let us see how we can calculate the factorial of 12

var factorial = 1;

for (i = 1; i <= 12; i++) {
    factorial = factorial * i;


console.log("the factorial of 12 is : " + factorial);Code language: JavaScript (javascript)

If you don’t know what a factorial is, google can be of great help.

Infinite JavaScript loop

Sometimes we might want to do something continuously. That is where infinite loop comes in. You might not find the everyday use case for this loop.

But there is certain use case for it in the long run. If you do JavaScript for long. You will find out exactly what I’m talking about.

But for now here is the syntax.

for (i = 0; i > -1; i++) {

    // do something really long

    i = i - 1; // reduce i by 1 because there is no use we just want to keep it constant(ish)
}Code language: JavaScript (javascript)

In the code above the condition ( i > -1 ) is always true. And we have learned from above that the loop will continue to run until it is false.

Hence, the loop will continue forever.

Related Posts