What is the difference between synchronous and asynchronous code in JavaScript?

Angelos Chalaris · Nov 14, 2021 ·

JavaScript, Function, Promise

Synchronous code runs in sequence. This means that each operation must wait for the previous one to complete before executing.

console.log('One');
console.log('Two');
console.log('Three');
// LOGS: 'One', 'Two', 'Three'

Asynchronous code runs in parallel. This means that an operation can occur while another one is still being processed.

console.log('One');
setTimeout(() => console.log('Two'), 100);
console.log('Three');
// LOGS: 'One', 'Three', 'Two'

Asynchronous code execution is often preferable in situations where execution can be blocked indefinitely. Some examples of this are network requests, long-running calculations, file system operations etc. Using asynchronous code in the browser ensures the page remains responsive and the user experience is mostly unaffected.

Recommended snippets

  • Asynchronously looping over arrays in JavaScript comes with a few caveats you should watch out for.

  • Learn everything you need to know about promises and asynchronous JavaScript with this handy cheatsheet.

  • What is a callback function?

    JavaScript, Article

    JavaScript uses callback functions in various places for different purposes. From event listeners to asynchronous operations, they are an invaluable tool you need to master.