Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.7 — Callbacks and Higher-Order Functions
JavaScript · Example 2 of 3

map, filter, reduce and a famous surprise

sort() without a callback compares items as strings, so "100" comes before "20". A compare callback fixes it.

In JavaScript, functions are values: you can store them, pass them to other functions (callbacks) and return them; a higher-order function is one that takes or returns a function, like map, filter, addEventListener and setTimeout.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write applyTwice(fn, value) that returns fn(fn(value)), and test it with n => n + 3 and 5.

02

Using filter and map, turn ["apple", "kiwi", "banana", "fig"] into the upper-case names of fruits longer than 3 letters.

03

Write logged(fn) that returns a new function which prints "result: " and the result each time, and returns the result.

Explain it without notes

01

What does it mean that functions are first-class in JavaScript?

02

What is a callback, and what is a higher-order function? Give two built-in examples of each idea.

03

What is the difference between a synchronous and an asynchronous callback?

04

Why does ["1", "2", "3"].map(parseInt) return [1, NaN, NaN]?

map, filter, reduce and a famous surprise

Console

(nothing was printed)

Expected console output

[ 240, 90, 600, 160 ]
[ 45, 80 ]
545
2 cheap items
[ '0:a', '1:b' ]
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]
[ 100, 20, 3 ]
[ 3, 20, 100 ]