In Java you can use a for each loop by saying:
for (elemento e : array)
Also in jQuery:
$.each(arr, function() {
In JavaScript I know I can do:
for (var i = 0; i > 10; i ++)
But is there a way to do a for each in pure JavaScript?
In Java you can use a for each loop by saying:
for (elemento e : array)
Also in jQuery:
$.each(arr, function() {
In JavaScript I know I can do:
for (var i = 0; i > 10; i ++)
But is there a way to do a for each in pure JavaScript?
Ways to iterate over Arrays and Objects in JavaScript
Array#forEach method
Object#keys method combined with Array#forEach method
for-i loop
for-in loop
for-of loop
Conclusion:
forEach
accepts a function as a callback . By passing this function, which acts as an iterator, it is called for each element of theArray
.*Note: Works as of ECMAScript 5.
call back
The function that is passed as the callback accepts 3 parameters: the value of the element, the index, and a reference to the array being iterated over. The last 2 are optional (the first example just passed the element). If we also wanted to use the index:
In addition, it should be noted that
.forEach
it does not mutate at all to thearray
. If the value of is changedelemento
, thearray
will not be modified (although it could be referenced to change the value).Other similar functions
.every()
Exits the loop as soon as the function returnsfalse
..some()
Exits the loop as soon as the function returnstrue
.As a note and correcting @dddenis's comment about iterating an object, comment that objects can also be iterated with this method.
The Object constructor has the Object.keys() method that returns an Array of the properties of a given object.
In this way we could iterate said Array and access the values of said properties as follows:
The foreach using await and async, check the next code: