Modern JavaScript Essentials

Lesson 2 of 6

Arrays and Higher-Order Functions

A higher-order function is simply a function that takes another function as an argument, or returns one. Arrays have several built-in higher-order functions that let you transform data without writing manual loops.

JavaScript

The three big ones

  • .filter(fn) builds a new array containing only the elements where fn returns true. Here, s => s >= 70 keeps every score of 70 or above.
  • .map(fn) builds a new array by transforming every element. Here, s => s * 2 doubles each score.
  • .reduce((acc, s) => ..., initialValue) combines every element into a single value. acc (the "accumulator") carries the running result forward from one element to the next, starting at initialValue (here, 0).

Why not just use a for loop?

You could write the same logic with a for loop, but map/filter/reduce say what you want ("give me only the passing scores") instead of how to get it (looping, checking, pushing to a new array). None of them modify the original array, scores is untouched after all three calls, that predictability is a big part of why they're the backbone of modern JavaScript.

📝 Array Methods Quiz

Passing score: 70%
  1. 1.Which method returns a new array with only the elements that pass a test?

  2. 2.Array.prototype.map mutates the original array.