Array Methods

Once you have an array, you rarely loop over it by hand. JavaScript gives arrays built-in methods for the jobs you'll need over and over: doing something with each item, transforming them into something new, keeping only some of them, or boiling the whole thing down to a single value.

forEach — run code for each item

forEach calls a function once per item, passing that item in. It doesn't build anything or hand anything back — it's for side effects, like logging:

Try it yourself
Console output

map — build a new array from an old one

map runs a function on every item and collects the return values into a brand new array — always the same length as the original. The source array is left completely alone:

Try it yourself
Console output

filter — keep only some items

filter's function returns true or false for each item. Only the items where it returned true make it into the new array:

Try it yourself
Console output

find — get the first match

find also runs a true/false test, but it stops at the first item that passes and returns that one item directly — not an array. If nothing matches, it returns undefined:

Try it yourself
Console output

reduce — combine everything into one value

reduce is the odd one out: its function carries a running value from one item to the next, and the final running value is what gets returned. The second argument to reduce is the starting point for that running value:

Try it yourself
Console output

Each pass, sum is whatever the function returned last time (starting at 0), and price is the next item in the array.

Note: map, filter, and reduce all return something new instead of changing the original array. That's exactly why they're safe to chain together, like cart.filter(p => p > 10).map(p => p * 1.2) — each step hands a fresh array to the next.