Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
for Loop in JavaScript: A Detailed Discussion with Examples

for Loop in JavaScript: A Detailed Discussion with Examples

08 Aug 2024
Beginner
469 Views
16 min read
Learn with an interactive course and practical hands-on labs

Free Javascript Course: Learn Javascript In 21 Days

for loop in JavaScript

A for loop in JavaScript is the first and most basic loop control structure. It executes a block of code for a certain number of times until a specified condition is evaluated as false. The JavaScript for loop is similar to the for loop in C, C++, or Java.

In this JavaScript tutorial, we'll explore the for loop control structure in JavaScript and understand its syntax, flowchart, nested, and infinite for loops with examples, etc.

Read More: JavaScript Interview Questions and Answers (Fresher + Experience)

What is JavaScript for loop?

A for loop is a control structure that enables a set of instructions to get executed for a specified number of iterations until the condition holds. It is an entry-controlled loop.

JavaScript for Loop Flowchart

for loop in JavaScript

JavaScript for loop Syntax


for (expression 1; expression 2; expression 3) {
  // code block to be executed
}
  • Expression 1: Initialization of the Counter Variable

    A counter variable keeps track of the number of iterations in the loop. There can be multiple counter-variables initialized in this expression separated by commas. You can also initialize the counter variable externally rather than in expression 1. Hence, this is an optional expression. This expression can also declare variables. We can leave the portion empty with a semicolon.

    Example of Initialization of Counter Variables

    
    const names = ["Sourav", "Sakshi", "Girdhar", "Amit"];
    let text = ""; //Declare text outside of the loop
    
    for (let i = 0, len = names.length; i < len; i++) {
      text += names[i] + " ";
    }
    
    console.log(`text: ${text}`);     

    In the above code, we've declared and initialized two variables in the expression 1 of the for loop.

    Output

    text: Sourav Sakshi Girdhar Amit        

    Example of for loop without the initializer

    
    let x = 1;
    
    for (; x <= 8; x++) {
        console.log("Value of x:" + x);
    } 

    In the above code, we've declared and initialized the counter variable before the for loop.

    Output

    Value of x:1
    Value of x:2
    Value of x:3
    Value of x:4
    Value of x:5
    Value of x:6
    Value of x:7
    Value of x:8 
  • Expression 2: Test Condition

    The test condition must return the true value for the loop to be executed. If the test condition is evaluated as false, the loop will end, and the code outside the loop will be executed. The for loop enters the body of the loop, and iteration starts based on the boolean true result of the test condition. On completion of one iteration of the loop, the condition is re-evaluated. This process will keep repeating until the condition is false.

    This is also an optional expression like expression 1. If you do not specify any test condition, it is assumed to be true. But in such cases, you must specify the break keyword in the loop body; otherwise, it'll turn into an infinite for loop. This can crash your browser.

    Example of for loop without the test condition

    
    let x = 7;
    for (; ; x++) {
        console.log("Value of x:" + x);
        break;
    }
    

    Output

    Value of x:7
    
  • Expression 3: Updation of the Counter Variable

    This expression increments/decrements the value of the counter/initial variable. Hence, it's also called an update expression or iterator. On each update, the test condition is evaluated. The body of the for loop executes until the test condition is evaluated as false. The iterator stops once the test condition becomes false.

    Again, this is an optional expression. You can update your counter variable inside the body of the for loop instead of putting it inside the parentheses () of the for loop.

    Example of for loop without the update expression

    
    const employees = ["Sourav", "Sakshi", "Girdhar", "Amit"];
    let i = 0;
    let len = employees.length;
    let text = "";
    for (; i < len;) {
        text += employees[i] + " ";
        //can be increased inside loop
        i++;
    }
    console.log(text)
    

    In the above code, for (; i < len;) indicates omitted initialization and update expression, focusing only on the test condition.

    Output

    Sourav Sakshi Girdhar Amit
    

We saw that all the expressions in the for-loop syntax are optional. So, the syntax of the for loop without any statements is:

JavaScript for loop Syntax without Expressions/Statements


for ( ; ; ) {
   // statements
}

Example of for loop Without any Expression


let i = 10;
for (;;) {
  if (i > 20) {
    break;
  }
  console.log(i);
  i += 2;
}

As all expressions are optional, we've omitted them in the () of the for loop in the above code. Instead, we've initialized the counter variable above the for loop. The test condition and update expression are also mentioned in the body of the for loop.

Output

10
12
14
16
18
20

JavaScript program illustrating a simple for-loop


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

The above code prints the numbers from 1 to 10 using a for loop in JavaScript.

IterationVariableCondition: i < 11Action
1i = 1true1 is printed. i is increased to 2.
2i = 2true2 is printed. i is increased to 3.
3i = 3true3 is printed. i is increased to 4.
4i = 4true4 is printed. i is increased to 5.
5i = 5true5 is printed. i is increased to 6
6i = 6true6 is printed. i is increased to 7
7i = 7true7 is printed. i is increased to 8
8i = 8true8 is printed. i is increased to 9
9i = 9true9 is printed. i is increased to 10
10i = 10true10 is printed. i is increased to 11.
11i = 11falseThe loop terminates

Output

1
2
3
4
5
6
7
8
9
10

for loop in JavaScript without the loop body

In JavaScript, you can keep the for loop body empty, i.e., no statements inside the body of the loop. To do this, you need to put the semicolon (;) immediately after the for statement.

Example of JavaScript for loop Without loop Body


let sum = 0;
for (let i = 0; i < 11; i++, sum += i);
console.log(sum);

The above code contains the for-loop statement with initialized counter variable, test condition, and update expression. The program calculates the sum of integers from 0-10. The loop increments the sum within the loop header.

Output

66

Nested for Loops in JavaScript

In JavaScript, it is a for loop inside a for loop. For each cycle of the outer loop, the inner loop completes its entire sequence of iterations.

JavaScript Nested for Loop Flowchart

Nested for loop in JavaScript

Example of Nested for Loop in JavaScript


for (let i = 1; i <= 5; i++) {
    let line = "";
    for (let j = 1; j <= i; j++) {
        line += j + " ";
    }
    console.log(line.trim());
}
  • This JavaScript code generates a pattern of numbers using nested loops.
  • The inner loop j iterates from 1 to the current value of i, printing numbers and spaces.
  • The outer loop i iterates from 1 to 5, regulating the number of rows.
  • As a result, there is a pattern of numerals rising in each row, with a new line between each row.

JavaScript Infinite for loop

An infinite for loop gets created if the for loop condition remains true or if the programmer forgets to apply the test condition/terminating statement within the for loop statement.

Example of an infinite for loop in JavaScript


for (let i = 0; true; i++) {
    console.log("This loop will run forever!");
}

In the above code, the test condition is explicitly set to true. Hence, this loop will continue executing indefinitely. To save resources, such an infinite loop must be avoided.

Output

This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
This loop will run forever!
You can also read:
Summary

In the above article, we covered the for loop from all angles. We've explained the minute aspects of the loop control structure with proper examples to make your learning smooth and easy. Remember that loop control structures are the fundamental concepts of any programming language, and so are JavaScript. Therefore, in order to learn JavaScript thoroughly, go step by step and clear your fundamentals in our JavaScript Programming Course.

ScholarHat provides various Training and Certification Courses to help you in your end-to-end product development:

FAQs

 A for loop in JavaScript is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and iteration, which control the loop's execution. 

 The different types of loops in JavaScript are for, while, do...while, and for...in and for...of. 

A for loop in JavaScript is used with the syntax for (initialization; condition; increment) { // code to be executed }. It repeatedly executes the block of code as long as the specified condition is evaluated as accurate.

Take our Javascript skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this