Looping statement enable our JavaScript program to continuously execute a piece of code as long as a specified condition is true. Looping statement makes the JavaScript code compact. There are besically five types of looping statements-
A for loop repeats a piece of code until a specified condition is true. The for Loop has three important parts i.e. Initialization, Condition, and Increment/Decrement.
for (Initialization; Condition; Increment/Decrement) {
...........
}
for (i = 0; i <=5; i++) {
console.log(i);
}
The while loop is a more simple version of the for, which repeats a piece of code until a specified condition is true.
let i = 10;
while (i > 0) {
console.log(i);
i--;
}
The do-while loop is very similar to the while loop, but it executed at least once whether the condition is true or false, because condition check happens at the end of the loop.
let i = 0;
do {
i++;
console.log(i);
} while (i <= 5);
The for-in loop is a special kind of a loop in JavaScript which iterates over the properties name of an object, or the elements of an array.
let datas = [3, 5, 7, 9, 11];
for (var data in datas) {
console.log(data); // 0, 1, 2, 3, 4
}
The for-of loop is another special kind of a loop in JavaScript introduced in ES6, which iterates over the propertie value of an array.
let datas = [3, 5, 7, 9, 11];
for (var data of datas) {
console.log(data); // 3, 5, 7, 9, 11
}