Sub topic 1
Functions Are Values
Prerequisites
This chapter assumes you can write regular and arrow functions, work with arrays and objects, and run a script in Node.js or a browser console. It also assumes you know how let, const, and var differ in scope.
Functions Are Values
In JavaScript, a function is a value, just like a number or a string. You can store a function in a variable, put it in an array, return it from another function, or pass it as an argument. Passing a function as an argument is what makes callbacks possible.
const greet = (name) => `Hello, ${name}`;
const sayIt = greet; // no call, just a reference
console.log(sayIt('Ada')); // Hello, AdaWhat a Callback Is and How to Write One
A callback is a function you pass to another function so that the other function can call it. A function that accepts or returns functions is called a higher-order function.
The most common mistake is to pass the result of calling the function when you meant to pass the function itself.
Synchronous Callbacks: map, filter, forEach, and Your Own Higher-Order Functions
A synchronous callback runs before the higher-order function returns. Array methods such as map, filter, and forEach work this way, and so does any loop you write yourself.
function repeat(times, callback) {
for (let i = 0; i < times; i++) {
callback(i);
}
}
repeat(3, (n) => console.log('call', n));
// call 0
// call 1
// call 2
const doubled = [1, 2, 3].map((x) => x * 2);
console.log(doubled); // [2, 4, 6]Asynchronous Callbacks: setTimeout and I/O
An asynchronous callback runs later, after the current synchronous code has finished. Timers, file reads, and network requests all take callbacks like this. Even a zero-millisecond delay does not make the callback run immediately.
console.log('A');
setTimeout(() => console.log('C'), 0);
console.log('B');
// Output: A, B, CThe setTimeout callback has to wait until the code that is running now has finished. The next chapter explains the scheduling behind this.
Exercise
What does this script print, and in what order? console.log('1'); [1, 2].forEach((n) => console.log('each', n)); setTimeout(() => console.log('timer'), 0); console.log('2');
Show answer
It prints 1, each 1, each 2, 2, timer. The forEach callback is synchronous, so it runs in place. The setTimeout callback is asynchronous, so it runs only after all the synchronous code has finished.