Is JavaScript Synchronous or Asynchronous??

The basic idea behind the JavaScript synchronous and asynchronous behaviours.

By default JavaScript is single threaded and synchronous language. In synchronous way, the code executes sequentially. That means it will do one thing within one time unit and freeze the rest in meantime. Therefore executing in synchronously is time consuming.

Code

console.log("First Statement");
console.log("Middle Statement");
console.log("Last Statement");

Output

First Statement
Middle Statement
Last Statement

This is an example for synchronous code block. So, it is executed by JavaScript call stack as line after line. This becomes a very serious problem when you are working on a big application with a lot of server requests.

As a solution for this asynchronous model of programming was introduced. Asynchronous code allows to execute multiple code lines at the same time unit. So in a nutshell, JavaScript just became multi-threaded with the ability to perform multiple tasks simultaneously. This changes our definition to JavaScript is an asynchronous, non-blocking, multi-threaded language.

Now lets see what happens in asynchronous programming model.

JavaScript code is executed by JavaScript Engines like V8, SpiderMonkey, Rhino, KJS, Chakra, etc. All these engines have Web APIs that are responsible for handling the asynchronous code in the background. So these call stacks identify these asynchronous functions and passed them to handle by the browser. Once those tasks are finished by the browser, they return and are pushed onto the stack as a callback.

Code

console.log("First Statement");
setTimeout(()=>{
console.log("Within the function");
}, 1000)
console.log("Last Statement");

Output

First Statement
Last Statement
Within the function

Here the setTimeout() is an asynchronous function. So, it is not handled by the JavaScript call stack and passed it to Web API to be handled. While it is executed by the Web API, the rest will be executed by call stack.

Lets try another code in asynchronous model.

Code

console.log("First Statement");
setTimeout(()=>{
console.log("Within the 1 second function");
}, 1000)
setTimeout(()=>{
console.log("Within the 0 second function");
}, 0)
console.log("Last Statement");

Output

First Statement
Last Statement
Within the 0 second function
Within the 1 second function

Through above code, you can get an idea of how the Web API handle the asynchronus functions.

So, we can undestand that both asynchronous and synchronous behaviours can be found in JavaScript.

Hope you get an idea of asynchronous and synchronous behaviour in JavaScript.

Thank You….

Undergraduate at University of Moratuwa

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store