Loops in JavaScript repeat a block of code until a specified condition is met. They help automate repetitive tasks and reduce code duplication.
for
Loop
It is used when the number of iterations is known in advance.
var numbers = [1, 3, 5, 3, 7, 8, 9];
for(let i =0; i< numbers.length; i++)
{
console.log(numbers[i]);
}
Output:
1
3
5
3
7
8
9
while
Loop
This is used when the number of iterations is not known in advance (run when the condition is
true
).
Example:
var numbers = [1, 3, 5, 3, 7, 8, 9];
let i =0;
while(i <=numbers.length)
{
console.log(numbers[i]);
i++;
}
Output:
1
3
5
3
7
8
9
do...while
Loop
This ensures that the code is executed at least once, even if the condition is false.
Example:
var numbers = [1, 3, 5, 3, 7, 8, 9];
let i = 0;
do {
console.log(numbers[i]);
i++;
}
while (i <= numbers.length);
Output:
1
3
5
3
7
8
9
for...in
Loop (Used for Objects)
Iterates over the keys (properties) of an object.
Example:
let person = { name: "John", age: 30, city: "New York" };
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output:
name: John
age: 30
city: New York
for...of
Loop (Used for Arrays & Iterables)
Iterates over the values in an array or iterable object.
Example:
let numbers = [10, 20, 30, 40];
for (let num of numbers) {
console.log(num);
}
Output:
10
20
30
40
Loop Control Statements
- Break → Exits the loop immediately.
- Continue → Skips the current iteration and moves on to the next one.
Use break
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Stops at 3
}
console.log(i);
}
Output:
1
2
Use continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skips 3
}
console.log(i);
}
Output:
1
2
4
5
I hope you understand clearly all the types of javascript loop.
Thanks.
Also, read: LINQ to SQL LIKE operator with C#
Leave Comment