Loops are the main component of every programming language. Iteration or loop is a structure, series, or process, the end of which is connected to the beginning. But in programming, it allows repeating block code, until the given condition is true. In Javascript we have three basics types loops are available –
- for
- while
- do while
for loop
// for loop
for (var i = 0; i < 5; i++) {
console.info(i); // 0, 1, 2, 3, 4
}
while loop
// while loop
var i = 0;
while (i < 5) {
console.log(i); // 0, 1, 2, 3, 4
i++;
}
do while loop
// do while loop
var i = 0;
do {
console.log(i); // 0, 1, 2, 3, 4
i++;
} while( i< 5);
continue
continue to exit the current iteration in a loop.
for (var i = 0; i < 5; i++) {
if ( i % 2 == 0) continue; //skip this iteration
console.log(i); // 1, 3
}
break
break exits the loop completely.
for (var i = 0; i < 5; i++) {
if ( i % 2 != 0) break; // exits loop
console.log(i); //0
}
for in loop
for in for object don’t use it for an array
var obj = {
name: "Jhon",
age: 23
};
for (var key in obj) {
console.log(obj[key]); //Jhon, 23
}
forEach loop
// forEach loop
var obj = ["Jhon",23 ];
obj.forEach(function (key, val) {
console.log(val); // 0, 1
});
for…of
for-of is a new loop in ES6 that replaces both for-in and forEach() and supports the new iteration protocol.
// forEach loop
let arr = [1, 2, 3];
for (let val of arr) {
console.info(val); // 1, 2, 3
}