Loops and iterations in JavaScript are used to execute a block of code repeatedly. There are several types of loops available in JavaScript.
It executes a block of code for a specific number of times.
// for loop
for (initialization; condition; increment/decrement) {
// code to be executed
}
// for loop
for (let i = 0; i < 3; i++) {
console.log(i); // 0 1 2
}
It executes a block of code while a specified condition is true.
// while loop
while (condition) {
// code to be executed
}
// while loop
let i = 0;
while (i < 3) {
console.log(i); // 0 1 2
i++;
}
The code of block is executed once before the condition is checked.
// do-while
do{
// code to be executed
}while(condition);
// do-while
let i = 0;
do {
console.log(i);
i++;
} while (i < 3); // 0 1 2
Iterates over the enumerable properties of an object.
// for...in loop
for (variable in object) {
// code to be executed
}
// for...in loop
const person = {name: 'Wasif', age: 22, gender: 'male'};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Iterates over iterable objects (arrays, strings, maps, sets, etc.).
// for...of loop
for (variable of iterable) {
// code to be executed
}
// for...of loop
const skills = ['JavaScript', 'c++', 'python'];
for (let fruit of skills) {
console.log(skills);
}