Member-only story
Javascript is single-threaded? You’re kidding me!!!

It was a Saturday evening and was going through an Udemy course on Angular (a new skill am trying to acquire). In a few videos, I realized that my Typescript skills are bad and switched over to its documentation. Well, within a few topics, I got skeptical about my Javascript understanding, and I set about to start exploring some of the basics. And the result is this blog.
While it’s well-known fact that “Javascript is single-threaded language”, there was always some doubt about this. If Javascript is single-threaded, how does it support asynchronous calls? How come Node.js, based on javascript runtime, is non-blocking? These were some of the intriguing questions that occurred to me. And I decided to capture my train of thoughts here to connect the various dots involved in understanding the fundamentals of Javascript.
My Javascript Q&A
Q: What does single-threaded mean?
A: That there will be only one thread (process) available for the instructions to be executed.
Q: Ok, is Javascript single-threaded?
A: Yes, Javascript “runtime” is single-threaded. It executes the javascript program. It maintains a single stack where the instructions are pushed to control the order of execution and popped to get executed. And a heap space where the object references are stored and garbage collected.
Let’s look at this simple program and see how it is gets executed.
When the script (callstack.js) is executed, the javascript runtime creates a global execution context, pushes it into the stack (Fig 1, state 1), and scans further down. Next, the variable initialization (a = 10), will be pushed into the stack. Further to it is the main() function call. Unlike variable initialization for function calls, the runtime creates a new function execution context and pushes on top of the call stack (Fig1, state 2).