CS Engineering Gyan

JavaScript Loops

Loops are one of the most important concepts in JavaScript programming. A loop allows a program to execute the same block of code repeatedly until a specific condition becomes false.

In programming, many tasks require repeating the same operation multiple times. For example, displaying numbers from 1 to 100, printing student records, processing shopping items, or reading data from a database. Writing the same code again and again is not efficient, so loops are used to automate repeated tasks.

JavaScript provides different types of loops that help developers perform repetitive operations easily and efficiently. Understanding loops is essential for creating dynamic websites and web applications.


What are JavaScript Loops?

A loop is a programming structure that repeatedly executes a block of statements as long as a given condition remains true.

Instead of writing the same statement multiple times, developers can use loops to reduce code length and improve program efficiency.

For example, if we want to print numbers from 1 to 10, writing ten separate statements is unnecessary. A loop can perform this task using only a few lines of code.

Without Loop


document.write(1);
document.write(2);
document.write(3);
document.write(4);
document.write(5);

The above code becomes difficult to manage when we need to print hundreds or thousands of values.

Using Loop


for(let i = 1; i <= 5; i++)
{
    document.write(i);
}

The loop executes the same task multiple times with less code and better readability.


Why are Loops Important?

Loops make programs faster, shorter, and easier to maintain. Almost every modern application uses loops to handle repeated operations.

Advantages of Using Loops


How JavaScript Loops Work?

A loop generally contains three important parts:

  1. Initialization: Starting value of the loop variable.
  2. Condition: Determines whether the loop should continue or stop.
  3. Increment/Decrement: Changes the loop variable after every iteration.

Example Structure


initialization;

while(condition)
{

    // Code execution

    increment/decrement;

}

JavaScript checks the condition before every repetition. If the condition is true, the loop body executes. When the condition becomes false, the loop stops.


Types of JavaScript Loops

JavaScript provides different types of loops for different programming requirements.

Loop Type Description
for Loop Used when the number of iterations is known.
while Loop Used when a condition controls repetition.
do...while Loop Executes the block at least once before checking condition.
for...of Loop Used to iterate over iterable objects like arrays and strings.
for...in Loop Used to iterate through object properties.

JavaScript for Loop

The for loop is the most commonly used loop in JavaScript. It is generally used when we know how many times a block of code needs to execute.

A for loop combines initialization, condition, and increment/decrement in a single statement.

Syntax


for(initialization; condition; increment/decrement)
{

    // Statements to execute

}


Example 1: Print Numbers from 1 to 5


for(let i = 1; i <= 5; i++)
{

    document.write(i);

}

Output


1
2
3
4
5

In this example, the variable i starts from 1. The loop continues until the value of i becomes greater than 5.


Example 2: Print Even Numbers


for(let i = 2; i <= 10; i = i + 2)
{

    console.log(i);

}

Output


2
4
6
8
10

The loop increases the value by 2 after every iteration, which prints only even numbers.


Example 3: Calculate Sum of Numbers


let sum = 0;


for(let i = 1; i <= 5; i++)
{

    sum = sum + i;

}


document.write(sum);

Output


15

The loop adds numbers from 1 to 5 and stores the final result in the sum variable.



JavaScript while Loop

The while loop is a conditional loop in JavaScript that executes a block of code repeatedly as long as the specified condition remains true.

Unlike the for loop, the while loop is mainly used when the number of repetitions is not known in advance. The loop continues running until the condition becomes false.

Syntax


while(condition)
{

    // Statements to execute

}


How while Loop Works

  1. A variable is initialized before starting the loop.
  2. JavaScript checks the given condition.
  3. If the condition is true, the loop body executes.
  4. The loop variable is updated.
  5. The process continues until the condition becomes false.

Example 1: Print Numbers Using while Loop


let i = 1;


while(i <= 5)
{

    document.write(i);

    i++;

}

Output


1
2
3
4
5

In this example, the loop starts with value 1 and continues executing until the value of i becomes greater than 5.


Example 2: Display Multiplication Table


let number = 5;

let i = 1;


while(i <= 10)
{

    document.write(number * i);

    i++;

}

Output


5
10
15
20
25
30
35
40
45
50


JavaScript do...while Loop

The do...while loop is similar to the while loop, but there is one major difference. The do...while loop executes the code block at least one time before checking the condition.

This type of loop is useful when the program needs to perform an action first and then decide whether to repeat it.

Syntax


do
{

    // Statements

}

while(condition);


Example: do...while Loop


let i = 1;


do
{

    document.write(i);

    i++;

}

while(i <= 5);

Output


1
2
3
4
5


Difference Between while and do...while Loop

while Loop do...while Loop
Condition is checked before execution. Condition is checked after execution.
May execute zero times. Always executes at least once.
Used when execution depends on condition. Used when one execution is required before checking.
Syntax is shorter. Requires a do block before while.

Nested Loops in JavaScript

A nested loop means placing one loop inside another loop. The inner loop executes completely for every single execution of the outer loop.

Nested loops are commonly used for creating patterns, working with tables, and processing multi-dimensional data.

Syntax


for(initialization; condition; increment)
{

    for(initialization; condition; increment)
    {

        // Inner loop statements

    }

}


Example: Printing Pattern


for(let i = 1; i <= 3; i++)
{

    for(let j = 1; j <= i; j++)
    {

        document.write("*");

    }

    document.write("<br>");

}

Output


*
**
***

The outer loop controls the number of rows, while the inner loop controls the number of symbols printed in each row.


Infinite Loop in JavaScript

An infinite loop is a loop that never stops because its condition always remains true.

Infinite loops should be avoided because they can freeze the browser or consume unnecessary system resources.

Example


let i = 1;


while(i <= 5)
{

    document.write(i);

}

The above loop becomes infinite because the value of i is never increased.

Correct Example


let i = 1;


while(i <= 5)
{

    document.write(i);

    i++;

}


break Statement in JavaScript Loops

The break statement is used to immediately stop the execution of a loop. When JavaScript encounters break, the loop terminates and program execution continues after the loop.

Syntax


break;


Example Using break


for(let i = 1; i <= 10; i++)
{

    if(i == 5)
    {

        break;

    }

    document.write(i);

}

Output


1
2
3
4

When the value of i becomes 5, the break statement stops the loop immediately.


continue Statement in JavaScript Loops

The continue statement is used to skip the current iteration and move to the next iteration of the loop.

Unlike break, continue does not terminate the loop. It only skips specific values.

Syntax


continue;


Example Using continue


for(let i = 1; i <= 5; i++)
{

    if(i == 3)
    {

        continue;

    }

    document.write(i);

}

Output


1
2
4
5

The value 3 is skipped because the continue statement moves execution directly to the next iteration.


JavaScript for...of Loop

The for...of loop is used to iterate over iterable objects such as arrays, strings, maps, and sets.

It provides an easier way to access individual values without using indexes.

Syntax


for(variable of iterable)
{

    // Statements

}


Example: Array Iteration Using for...of


let fruits = ["Apple","Banana","Mango"];


for(let fruit of fruits)
{

    document.write(fruit);

}

Output


Apple
Banana
Mango


Example: String Iteration


let name = "JavaScript";


for(let character of name)
{

    console.log(character);

}

Output


J
a
v
a
S
c
r
i
p
t



JavaScript for...in Loop

The for...in loop is used in JavaScript to iterate through the properties of an object. It returns the keys or property names of an object one by one.

Unlike the for...of loop, which is used for values of iterable objects, the for...in loop is mainly designed for accessing object properties.

Syntax


for(variable in object)
{

    // Statements

}


Example: Access Object Properties


let student = {

    name: "Rahul",

    age: 20,

    course: "Computer Science"

};


for(let key in student)
{

    document.write(key + " : " + student[key]);

}

Output


name : Rahul

age : 20

course : Computer Science

In this example, the loop variable key stores each property name of the object and accesses the corresponding value using bracket notation.


Example: Counting Object Properties


let employee = {

    id:101,

    name:"Amit",

    department:"IT"

};


let count = 0;


for(let property in employee)
{

    count++;

}


document.write(count);

Output


3


Difference Between for...of and for...in Loop

for...of Loop for...in Loop
Used to access values. Used to access object properties.
Works with arrays, strings, maps, and sets. Mainly used with objects.
Returns element values. Returns property keys.
Cannot directly iterate normal objects. Can iterate object properties.

Loop Control Statements in JavaScript

Loop control statements are used to change the normal execution flow of loops. They allow developers to stop loops, skip iterations, or control repetition according to program requirements.

JavaScript mainly provides two loop control statements:


JavaScript Loops with Arrays

Arrays store multiple values in a single variable. Loops make it easier to access and process each element of an array.

Example: Display Array Elements


let numbers = [10,20,30,40,50];


for(let i = 0; i < numbers.length; i++)
{

    document.write(numbers[i]);

}

Output


10
20
30
40
50

The length property returns the total number of elements present in the array.


Example: Calculate Array Sum


let numbers = [5,10,15,20];

let sum = 0;


for(let i = 0; i < numbers.length; i++)
{

    sum = sum + numbers[i];

}


document.write(sum);

Output


50


Loops with User Input

Loops are commonly used with user input to perform repeated tasks. For example, taking multiple values from users, generating reports, or processing records.

Example: Print User Selected Range


let limit = 5;


for(let i = 1; i <= limit; i++)
{

    document.write(i);

}

Output


1
2
3
4
5


Real-World Applications of JavaScript Loops

Loops are used in almost every modern web application. They help developers handle repeated tasks automatically.


Difference Between JavaScript Loops

Loop Usage
for Loop Used when the number of iterations is known.
while Loop Used when repetition depends on a condition.
do...while Loop Executes at least once before checking condition.
for...of Loop Used for accessing iterable values.
for...in Loop Used for accessing object properties.

Common Mistakes While Using Loops


Best Practices for JavaScript Loops


JavaScript Loops Interview Questions

  1. What is a loop in JavaScript?
  2. Why are loops used in programming?
  3. Explain the difference between for and while loops.
  4. What is the purpose of the do...while loop?
  5. What happens if a loop condition never becomes false?
  6. Explain nested loops with an example.
  7. What is the difference between break and continue statements?
  8. What is the use of the for...of loop?
  9. What is the purpose of the for...in loop?
  10. Can we use for...in loop with arrays?
  11. How can we stop a loop in JavaScript?
  12. What is an infinite loop?
  13. How are loops used with arrays?
  14. Which loop is best when the number of iterations is known?
  15. Which loop executes at least one time?

Summary

JavaScript loops are powerful programming structures that allow developers to execute repeated tasks efficiently. The main loops available in JavaScript are for loop, while loop, do...while loop, for...of loop, and for...in loop.

The for loop is useful when the number of repetitions is known, while the while and do...while loops are useful when repetition depends on conditions. The for...of loop helps in accessing values from arrays and strings, whereas the for...in loop is used to access object properties.

A strong understanding of loops is necessary for advanced JavaScript concepts such as arrays, functions, DOM manipulation, events, and asynchronous programming. By mastering loops, developers can create efficient, dynamic, and interactive web applications.


← Previous: JavaScript Conditions Next: JavaScript Functions →
Home Visit Our YouTube Channel