JavaScript is a single-threaded programming language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece of code before moving into the next. However, thanks to the V8 engine, JavaScript can be asynchronous which means we can execute multiple tasks in our code at one time. So, in this article, I decided to show you the difference between Synchronous and Asynchronous code in JavaScript.

JavaScript Code.

Photo by Irvan Smith on Unsplash

Synchronous JavaScript

Synchronous code in JavaScript will start from the top of a file and execute all the way to the bottom, each line in order until it gets the bottom and it will stop. For example, if a function takes a while to execute or has to wait on something, it freezes everything up in the meanwhile because synchronous code in JavaScript can only do one task at a time, it waits until a particular statement has executed then it moves to the next one. A good example of this happening is the window alert function **alert("Hello World")**** :**

Synchronous Code in JavaScript.

You can’t interact with the webpage at all until you hit OK and dismiss the alert.

Asynchronous JavaScript

We mentioned above that JavaScript is a single-threaded language, So how do we get asynchronous code with JavaScript then?

Well, the JavaScript engine has a web API that handles tasks in the background. The call stack recognizes functions of the web API and hands them off to be handled by the browser. Once those tasks are finished by the browser, they return and pushed onto the stack as a callback. That can help execute multiple functions at one time. So, asynchronous code starts executing from the top to the bottom of a file, but during that execution, it will run into some asynchronous functions where it will split off and execute that asynchronous code separately from the rest of the code at the same time. Let’s look at a simple example:

Asynchronous Code in JavaScript.

In the example above, the first line of code will start executing because It is on the stack first, so “first” gets printed. then it will move to the next line where the javascript engine will notice an asynchronous function **setTimeout **thatrequires 1000 milliseconds to be executed, So the engine will push it off to the WebAPI to be done asynchronously. The call stack moves on without caring about the code handed off to the Web APIs and **console.log("three")** is printed.

#programming #javascript #technology #asynchronous #web-development

Understanding Synchronous and Asynchronous Code in JavaScript
1.45 GEEK