Callback Functions
In Chapter
4âs section on the Array
object, I wrote that there are some methods dependent on
functions that are invoked automatically based on some event. The
Array
methods are filter
, forEach
, every
, map
,
and some
, and the functions used are
function literals, though when used in this manner, theyâre usually
referred to as callback functions.
Returning to the Array
methods,
the filter
method ensures that
elements are not added to any element unless they pass certain criteria.
Rather than have to test a value and then add to an array, you can just
toss everything at the array and let filter
take care of the work for you. The
forEach
method takes a function
thatâs then processed against each element. Unlike filter
, the array is not impacted by the
function.
The every
method runs the
callback function against every element in the array until one returns a
false
value. The map
method runs the callback function against
all the array elements and creates a new array from the results.
Finally, the some
method is the
opposite of every
, in that it runs
the callback function against every element until one returns a true
value.
Each callback function has three parameters: element
, index
, and array
. Some return a value, others donât. None
impact the original array.
Example
5-4 demonstrates how to use a callback function with an Array
. In this example, the original array contains elements that are themselves an array containing color values in a range of 0â255. After ...
Get Learning JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.