What does asynchronous mean in JavaScript?
Asynchronous code does not finish before the next statement starts. The runtime puts the work in a queue and moves on, and the work happens later when the runtime comes back to it. That is exactly what lets a page stay responsive while a network request is still on its way.
console.log('1 - synchronous');
setTimeout(function () {
console.log('3 - timeout callback');
}, 0);
Promise.resolve().then(function () {
console.log('2 - promise callback');
});
console.log('4 - synchronous again');
The order of the output is the important part, and it surprises people. The synchronous lines run first, in the order you wrote them. Then the promise callback runs, and only after that does the timeout callback run, even though the timer was set up first. The reason is that the runtime empties the queue of small jobs, which is where promise callbacks live, before it moves on to the next big job such as a timer.
There are two families of asynchronous work in the language. Callback-based APIs, such as setTimeout and addEventListener, schedule a function to be called later. Promise-based APIs give you back an object that you can attach handlers to, and those handlers run in the small-jobs queue. That is why they get to run before the next timer callback or input callback.
One point is worth making clear in an interview. Asynchronous does not mean parallel. JavaScript runs your code on a single thread, both in the browser and in a Node process, so two pieces of your code never run at the same moment. What asynchronous buys you is the ability to wait for something slow without blocking the thread, and the runtime uses that waiting time to handle input, paint the page, or answer other requests.