Synchronous vs asynchronous code in JavaScript

Let's consider the following code:

console.log('1'); console.log('2');

Obviously, the first output to the console will work first, and then the second one. That is, the commands of our code are executed in turn - in the order they appear in the code. Such a code is called synchronous.

And now we consider the next code:

setTimeout(function() { console.log('1'); }, 3000); console.log('2');

In this case, the commands are not executed in the order they appear in the code: the first output to the console will be executed when its time comes, but the rest of the code doesn't wait for this moment, but continues to be executed. Such a code is called asynchronous.

Asynchronous code occurs quite often in JavaScript: when working with timers, when binding event handlers, when loading images, when working with AJAX technology, which allows you to load parts of the page from the server, when working with NodeJS, which is server-side JavaScript.

enru