The Event Loop
Since JavaScript is single-threaded, callbacks are required to keep the main thread free – the basic idea is that you give the engine a function to call when something happens, where you can handle it, and then return the control to whatever other code needs to run.
Note
In more recent versions of browsers and Node.js, you can create threads via Web Workers on the browser or via Worker Threads in Node.js. However, these are usually saved for CPU-intensive tasks, and they are not as easy to use as callbacks or other alternatives are (for example, Promises – explored in more detail in Chapter 13, Async Await in TypeScript).
To illustrate this, let's look at a version of some JavaScript code where there are no callbacks, and we want to create a simple server that greets the users by their name:
// server.ts function logWithTime(message: string) { console.log(`[${new Date().toISOString()}]: ${message}`); } http .createServer...