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 the array ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access