Rajat Gupta
Rajat's Blog

Rajat's Blog

JavaScript: single threaded and synchronous

JavaScript: single threaded and synchronous

Rajat Gupta's photo
Rajat Gupta
ยทFeb 1, 2022ยท

3 min read

Subscribe to my newsletter and never miss my upcoming articles

A few days ago single threaded and synchronous were just 2 heavy words for me. If this is you right now, don't worry I'll try my best to make you understand.

So, let's get started:

Single threaded and synchronous are not that much different.

Single threaded: It can do only 1 thing at a time and has a single call stack (don't worry just read and soon you'll get what it is)

Synchronous: As the name suggests synchronous means to be in a sequence. So, basically a function has to wait for the earlier function to get executed and everything stops until the wait is over.

call stack is basically a data structure which records where in the program we are. If we step into a function we push it to the top of the stack and when we return a value from the function we basically pop the function off from the stack.

Let's understand it by running the below code:

function multiply(a, b){
     return a*b;
}

function square(n){
     return multiply(n)
}

function printSquare(n){
     let squared = square(n)
     console.log(squared)
}

printSquare(4)

๐Ÿ‘‡See how the above code executes: There will be a main() function when the file starts executing then we call printSquare which gets pushed over top of the stack which in turn calls square function which gets pushed over at the top of the stack which in turn calls the multiply function which gets pushed over at the top of the stack.

20220202_020605.jpg

Now, as soon as a function returns some value it gets popped off from top of the stack. Even if a function does not have anything to return, it gets popped off from top of the stack after its execution (printSquare(4)). ๐Ÿ‘‡ See below:

20220202_021639.jpg

Due to this synchronous nature of JavaScript problem arises when we have a very heavy function in between which is taking 20-30 seconds or more time to execute. In this case everything else is stopped (does not matter where you click in the browser window) for some time and the call stack gets blocked until that function returns.

To tackle this problem in JavaScript we made JavaScript asynchronous (where tasks seems to run in parallel) with the help of web API's. Actually, it only appears to be asynchronous, it still has only one call stack. I'll explain this concept in my next blog and will give its link here once ready.

If you have any doubts feel free to post in the comment section, I'll try to answer as many doubts as I can.

I write one article every day related to web-development (yes, every single f*cking day). Follow me here if you are learning the same..

Have an awesome day ahead ๐Ÿ˜€!

my twitter handle: @therajatg

If you are the linkedin type, let's connect: linkedin.com/in/therajatg

ย 
Share this