Sync vs async callbacks, and a wrapper
The forEach callback runs during the script; the timer callback waits until the script ends, even with a 0 ms delay. once is a higher-order function that returns a wrapped function.
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]?
Preview
Console
Nothing logged yet.Expected console output
1. script starts
2. forEach callback, item 1
2. forEach callback, item 2
4. script ends
5. timer callback runs later