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.
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.
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.
for(let i = 1; i <= 5; i++)
{
document.write(i);
}
The loop executes the same task multiple times with less code and better readability.
Loops make programs faster, shorter, and easier to maintain. Almost every modern application uses loops to handle repeated operations.
A loop generally contains three important parts:
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.
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. |
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.
for(initialization; condition; increment/decrement)
{
// Statements to execute
}
for(let i = 1; i <= 5; i++)
{
document.write(i);
}
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.
for(let i = 2; i <= 10; i = i + 2)
{
console.log(i);
}
2 4 6 8 10
The loop increases the value by 2 after every iteration, which prints only even numbers.
let sum = 0;
for(let i = 1; i <= 5; i++)
{
sum = sum + i;
}
document.write(sum);
15
The loop adds numbers from 1 to 5 and stores the final result in the sum variable.
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.
while(condition)
{
// Statements to execute
}
let i = 1;
while(i <= 5)
{
document.write(i);
i++;
}
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.
let number = 5;
let i = 1;
while(i <= 10)
{
document.write(number * i);
i++;
}
5 10 15 20 25 30 35 40 45 50
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.
do
{
// Statements
}
while(condition);
let i = 1;
do
{
document.write(i);
i++;
}
while(i <= 5);
1 2 3 4 5
| 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. |
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.
for(initialization; condition; increment)
{
for(initialization; condition; increment)
{
// Inner loop statements
}
}
for(let i = 1; i <= 3; i++)
{
for(let j = 1; j <= i; j++)
{
document.write("*");
}
document.write("<br>");
}
* ** ***
The outer loop controls the number of rows, while the inner loop controls the number of symbols printed in each row.
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.
let i = 1;
while(i <= 5)
{
document.write(i);
}
The above loop becomes infinite because the value of i is never increased.
let i = 1;
while(i <= 5)
{
document.write(i);
i++;
}
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.
break;
for(let i = 1; i <= 10; i++)
{
if(i == 5)
{
break;
}
document.write(i);
}
1 2 3 4
When the value of i becomes 5, the break statement stops the loop immediately.
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.
continue;
for(let i = 1; i <= 5; i++)
{
if(i == 3)
{
continue;
}
document.write(i);
}
1 2 4 5
The value 3 is skipped because the continue statement moves execution directly to the next iteration.
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.
for(variable of iterable)
{
// Statements
}
let fruits = ["Apple","Banana","Mango"];
for(let fruit of fruits)
{
document.write(fruit);
}
Apple Banana Mango
let name = "JavaScript";
for(let character of name)
{
console.log(character);
}
J a v a S c r i p t
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.
for(variable in object)
{
// Statements
}
let student = {
name: "Rahul",
age: 20,
course: "Computer Science"
};
for(let key in student)
{
document.write(key + " : " + student[key]);
}
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.
let employee = {
id:101,
name:"Amit",
department:"IT"
};
let count = 0;
for(let property in employee)
{
count++;
}
document.write(count);
3
| 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 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:
Arrays store multiple values in a single variable. Loops make it easier to access and process each element of an array.
let numbers = [10,20,30,40,50];
for(let i = 0; i < numbers.length; i++)
{
document.write(numbers[i]);
}
10 20 30 40 50
The length property returns the total number of elements present in the array.
let numbers = [5,10,15,20];
let sum = 0;
for(let i = 0; i < numbers.length; i++)
{
sum = sum + numbers[i];
}
document.write(sum);
50
Loops are commonly used with user input to perform repeated tasks. For example, taking multiple values from users, generating reports, or processing records.
let limit = 5;
for(let i = 1; i <= limit; i++)
{
document.write(i);
}
1 2 3 4 5
Loops are used in almost every modern web application. They help developers handle repeated tasks automatically.
| 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. |
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.