DEV Community

JOSHIK27
JOSHIK27

Posted on

IS JAVASCRIPT SYNCHRONOUS OR ASYNCHRONOUS ????

What is JAVASCRIPT ?

A scripting language which gives life to website by performing some logical operations on DOM elements

BEING MORE PRECISE

Javascript is SINGLE THREADED SYNCHRONOUS programming language with some asynchronous capabilities provided by browser.
Ooooo its so much of complex terms !!!

Let me break it down to small chunks to make it clear

  • SINGLE THREADED : Only one line of code will be executed at a time. We only have one call stack where each instruction is passed (like assigning variables, calling functions). So, each operation is executed and popped out as next instruction is going to be pushed from the top.

SIMPLEST EXAMPLE :

Image description

  • SYNCHRONOUS : It simply means, program will continue to execute an operation or function by blocking all other operations/code. This results in unresponsiveness to our website. This is simple inability of parallel tasks execution.

Let us understand with an example

Image description

So, here for loop takes significant amount time to run. Hence, below part of loop will keep waiting until loop is done with its execution. This is called synchronous nature as operations are being performed sequentially from top to bottom. We can see the blocking nature here. But usually we don't write such heavy operation intentionally but there are few operations like making requests to a server which takes significant amount of time to get the response back.
Hence, this is a problem. This make our website unresponsive !

THIS PROBLEM IS SOLVED BY BROWSER API'S

After running javascript file in browser, it creates a window object which contains web api's like setTimeOut, setInterval, fetchApi etc.

HOW BROWSER SOLVES THIS

Image description

As per our current knowledge what we expect is , first hi will be printed, then response variable will be assigned with some response by fetch (this step blocks the below code as it takes some time) and then bye is printed.

BUT THAT DOES NOT HAPPEN HERE !!!

Image description

First hi is printed, then browser web api is called, this will not execute in main thread !! but in different thread provided by browser. Meanwhile below code will be executed !!!! Once every operation below fetch operation is executed main call stack (main thread of execution) will be empty, then response will be assigned with value of fetch api.

This is called event loop on a high level.

THEREFORE JAVASCRIPT IS A SINGLE THREAD SYNCHRONOUS LANGUAGE WITH ASYNC BEHAVIOUR PROVIDED BY BROWSER WEB API'S

THIS IS MY FIRST BLOG HERE !
FEEDBACKS ARE APPRECIATED

JavaScript

Top comments (0)