While attempting to explain JavaScript's reduce method on arrays, conceptually, I came up with the following - hopefully it's helpful; happy to tweak it if anyone has suggestions.
| method name | callback is a predicate? | what does the callback answer? | what arguments does the callback get? | what is the final return value? |
|---|---|---|---|---|
forEach |
no | here’s an item. do something nutty with it, i don't care what. | item, index, list |
nothing - in other words, undefined |
map |
no | here’s an item. what should i replace it with? | item, index, list |
list of new items |
filter |
yes | should i keep this item? | item, index, list |
list of kept items |
reduce |
no | here’s the result from the previous iteration. what should i pass to the next iteration? | result, item, index, list |
result of last iteration |
reduceRight |
no | (same as reduce, but in reversed order: last-to-first) |
||
some |
yes | does this item meet your criteria? | item, index, list |
true after the first item that meets your criteria, else false |
every |
yes | does this item meet your criteria? | item, index, list |
false after the first item that failed to meet your criteria, else true |
find |
yes | is this item what you’re looking for? | item, index, list |
the item you’re looking for, or undefined |
findIndex |
yes | is this item what you’re looking for? | item, index, list |
the index of the item you’re looking for, or -1 |
- note: a "predicate" is a function that returns a boolean - ie,
trueorfalse. (technically it will accept any truthy or falsy value, and effectively coerce it to a boolean for you)