General/Legacy For Loop:
for(in):
for(of):
forEach loop:
Limitation of forEach loop: We can't break or skip the loop. It will iterate for all elements.
Note: "break" & "continue" are valid keywords and are allowed to use in other for loops.
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.
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. }
var array =[3,4,5,6,8,9]; for(var i of array) { console.log(i); //Here "i" will print element }
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 });
//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); } });
Comments
Post a Comment