In JavaScript, loops are control structures that allow you to execute a block of code repeatedly.
There are several types of loops in JavaScript, including for, while, do…while, and
the relatively newer for…of and for…in loops
1. For Loop:
The for loop is used when you know how many times you want to execute a block of code. It consists of three parts: initialization, condition, and increment/decrement.
Syntax
Example
2. While Loop:
The while loop repeats a block of code as long as a specified condition is true.
Syntax
Example
3. Do...While Loop:
Similar to the while loop, but the block of code is executed at least once before the condition is tested.
Syntax
Example
4. For...In Loop:
This loop iterates over the enumerable properties of an object, in arbitrary order. It’s often used for iterating over the properties
of an object.
Syntax
Example
// Output:
5. For...Of Loop:
Introduced in ES6, this loop iterates over iterable objects like arrays, strings, maps, sets, etc., in the order of their elements.
Syntax
Example
Main Difference between for...in Loop and for...of Loop
// Define an array with some elements
const myArray = [‘a’, ‘b’, ‘c’];
// Add a custom property to the array prototype
Array.prototype.customProperty = ‘Hello’;
// Now, let’s iterate over the array using for…in loop
console.log(“Using for…in loop:”);
for (let index in myArray) {
console.log(index); // Outputs: 0, 1, 2, customProperty
}
// Now, let’s iterate over the array using for…of loop
console.log(“Using for…of loop:”);
for (let value of myArray) {
console.log(value); // Outputs: ‘a’, ‘b’, ‘c’
}