Different Formats of For loop

General/Legacy For Loop:
var array =[3,4,5,6,8,9];
for(var i=0;i<array.length;i++)
console.log(array[i]); //Output: Prints all the elements of the array.

for(in):
var array =[3,4,5,6,8,9];
for(var i in array)
{
console.log(i); //Here "i" will print indexes
console.log(array[i]); // Here "i" will print elements.
}

for(of):
var array =[3,4,5,6,8,9];
for(var i of array)
{
console.log(i); //Here "i" will print element
}

forEach loop:
var array=[3,99,66,55,88];
array.forEach(function(element,index){
console.log(element); //prints all the elements.
console.log(index); // prints all the indexes
});

Limitation of forEach loop: We can't break or skip the loop. It will iterate for all elements. 

//Below code is valid
var array=[3,99,66,55,88];
array.forEach(function(element,index){
if(index==2){
console.log(element); //prints all the elements.
console.log(index); // prints all the indexes
}
});

//Below code is invalid, error is "VM1453:4 Uncaught SyntaxError: Illegal break statement"
var array=[3,99,66,55,88];
array.forEach(function(element,index){
if(index==2){
break;
}
});


//Below code is invalid, error is "VM1453:4 Uncaught SyntaxError: Illegal continue statement"
var array=[3,99,66,55,88];
array.forEach(function(element,index){
if(index==2){
continue;
}
else
{
 console.log(element);
}
});

Note: "break" & "continue" are valid keywords and are allowed to use in other for loops.

Comments