JavaScript has several statements for looping over an array but it also has two methods achieving a similar behavior.

The forEach method is the common method used to iterate over an array. It gives access to the current element and index but it cannot stop, it processes all the elements in the array.

The every method is not usually used to iterate over an array but may also accomplish this task and stop.

forEach

The forEach method executes the given callback function for each element in the array.

The forEach method invokes a callback with two arguments. The first one is the element itself which in that case is a function. The second argument is the index of the element.

every

Consider that you have an array that may also contain null elements and we want to stop once we find the first null value.

This not possible with the forEach method, it process all the elements in the array.

The every method is usually used to tests if all elements in the array pass the test implemented by the given predicate function. It returns a boolean value.

Nonetheless, the every method can also execute the given callback function for each element in the array as long as the callback returns true. It stops if the callback returns false.

As long as the callback returns true the every method continues processing the next element.

The loop stops at index 3, meaning the 4th element because the callback returns false at that point. The if (f === null) return false; is the stop condition.

Tags: , , , , , , , , , , , , , , , , , , , , , ,
java2days conference link

Most popular in DevStyleR

Update One

Update One

10 May, 2022
Gameloft

Gameloft

9 May, 2022
Droxic

Droxic

27 April, 2022
Tarya Fintech Bulgaria
Carista

Carista

19 April, 2022