The classic and famous for loop iterates over each item in the array. The for loops through a block of code a number of times:
The for uses 3 expressions:
The for...in loops through the properties of an object. It is among the most used and straightforward methods for iterating over objects:
The while loops through a block of code as long as a specified condition is true:
In the given example, the code in the loop will run over and over again, as long as a variable (i) is less than 10.
You can use break and continue in a while loop. But when you use the while loop you should take into account the increment for the next iteration. If you do not, then it may result in an infinite loop.forEach()
An alternative to for and for/in loops isArray.prototype.forEach(). The forEach() runs a function on each indexed element in an array. Starting at index a function will get called on index, index, index, etc… forEach() will let you loop through an array nearly the same way as a for loop:
The forEach() is not functional, as the function it takes as the input parameter is not supposed to return a value, thus cannot be regarded as a pure function.
The map() method creates a new array with the results of calling a function for each array element.
At first sight, the map() method has similarities with the forEach() method since it will also invoke the callback function once for each array element. The difference is that map() creates and returns new arrays based on the callback function result.