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.
Write applyTwice(fn, value) that returns fn(fn(value)), and test it with n => n + 3 and 5.
Using filter and map, turn ["apple", "kiwi", "banana", "fig"] into the upper-case names of fruits longer than 3 letters.
Write logged(fn) that returns a new function which prints "result: " and the result each time, and returns the result.
Explain it without notes
What does it mean that functions are first-class in JavaScript?
What is a callback, and what is a higher-order function? Give two built-in examples of each idea.
What is the difference between a synchronous and an asynchronous callback?
Why does ["1", "2", "3"].map(parseInt) return [1, NaN, NaN]?
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 ]