Search lands in PR-5.1 (Pagefind).

Explanation Intermediate

Chapter 10 Updated

Higher-Order Functions, map, filter & reduce

Higher-order functions + map, filter, reduce — functional JS patterns and polyfills.

  • Full 11m
  • Revision 3m
  • Flow 2m

The three musketeers — same shape, three outcomes

flowchart TD
    A["<b>i · Input array</b><br/>[5, 1, 3, 2, 6]"]
      --> CB["<b>ii · Pick your HOF</b><br/>map · filter · reduce"]
    CB --> M["<b>iii · map(cb)</b><br/>callback returns a value"]
    CB --> F["<b>iv · filter(cb)</b><br/>callback returns a boolean"]
    CB --> R["<b>v · reduce(cb, init)</b><br/>callback returns the new accumulator"]
    M --> MO["<b>vi · New array</b><br/>same length, transformed<br/><code>[10, 2, 6, 4, 12]</code>"]
    F --> FO["<b>vii · New array</b><br/>subset of input<br/><code>[5, 6]</code> (x &gt; 3)"]
    R --> RO["<b>viii · Single value</b><br/>of any type<br/><code>17</code> (sum)"]
 
    classDef input  fill:#f5efe1,stroke:#6a8a4f,stroke-width:2px,color:#1a1915;
    classDef hub    fill:#fdecd3,stroke:#c2410c,stroke-width:2px,color:#1a1915;
    classDef map    fill:#e7efd9,stroke:#587640,stroke-width:2px,color:#1a1915;
    classDef filt   fill:#e7efd9,stroke:#587640,stroke-width:2px,color:#1a1915;
    classDef red    fill:#e7efd9,stroke:#587640,stroke-width:2px,color:#1a1915;
    classDef out    fill:#f5efe1,stroke:#6a8a4f,stroke-width:2px,color:#1a1915;
    class A input
    class CB hub
    class M map
    class F filt
    class R red
    class MO,FO,RO out
  • Input array

    The array you call the method on. None of the three mutate it.

  • Pick your HOF

    map, filter, and reduce are all HOFs on Array.prototype — each takes a callback.

  • map(cb)

    Callback signature `(value, index, array)`. Whatever the callback returns becomes the new element.

  • filter(cb)

    Same callback signature. Truthy return keeps the element; falsy drops it.

  • reduce(cb, init)

    Callback `(acc, value, index, array)`. Return the new accumulator. Always pass an initial value.

  • map output

    A new array of the same length, with each element transformed.

  • filter output

    A new array containing only the elements that passed the predicate.

  • reduce output

    A single value of any type — a sum, max, object, grouped map, flattened array, anything.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.