What are the different types of Loops in JavaScript?

Loops in JavaScript: JavaScript provides several types of loops that allow you to iterate over data or execute a block of code repeatedly. Loops in JavaScript are used to execute a block of code repeatedly until a specific condition is met. There are several loops in JavaScript, including for, while, do-while, for-in, and for-of loops. This article explains loops in JavaScript in detail with code examples.

Different Types of Loops in JavaScript
Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. JavaScript now supports five different types of loops:
1) while
2) do…while
3) for
4) for…in
5) for…of

1) While loop
The while loop executes a block of code as long as a specified condition is true. It checks the condition before each iteration and stops when the condition is false. The while loop is used when you don’t know the number of iterations you want to perform in advance. It continues to execute the loop as long as the condition is true.

Example:

let i = 0;
while (i < 10) {
console.log(i);
i++;
}

2) Do-while loop
The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition. The do-while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once, even if the condition is false.

Example:

let i = 0;
do {
console.log(i);
i++;
} while (i < 10);

3) For loop
The for loop is the most commonly used loop in JavaScript. It has three parts: the initialization, the condition, and the final expression. The initialization is executed only once at the beginning of the loop, the condition is checked before each iteration, and the final expression is executed at the end of each iteration. The for loop is used when you know the number of iterations you want to perform. It is commonly used to iterate over arrays and other iterable objects.

Example:

for (let i = 0; i < 10; i++) {
console.log(i);
}

4) For-in loop
The for-in loop is used to loop through the properties of an object. The for-in loop is used to loop through the properties of an object. It is commonly used for iterating over the keys of an object.

Example:

const obj = { a: 1, b: 2, c: 3 };
for (const prop in obj) {
console.log(prop, obj[prop]);
}

5) For-of loop
The for-of loop is used to loop through the elements of an iterable object, such as an array or a string. The for-of loop is used to loop through the values of an iterable object, such as an array or a string. It is commonly used to iterate over arrays.

Example:

const arr = [1, 2, 3];
for (const element of arr) {
console.log(element);
}

Javascript training in hyderabad

contact

Enquiry Now
close slider
Scroll to Top
Call Now Button