Javascript interview cheat-sheet

all about single thread in javascript

ยท

2 min read

Javascript interview cheat-sheet

Hey Learners!๐Ÿ‘‹

Today here I am with another article.๐Ÿ˜

In this post, we will discuss a single thread

what is a single thread in javascript?

JavaScript is known to be single-threaded because of its property of having only one call stack, which some other programming languages have multiple. JavaScript functions are executed on the call stack, by LIFO (Last In First Out).

For example: we have a piece of code like this:

const foo = () => {
  const bar = () => {
    console.trace();
  }
  bar();
}

foo();

And the call stack will have foo to enter into the call stack, then bar.

single thread.png

After bar() is done, it will be popped off from the call stack, followed by foo(). You will see an anonymous function underneath when printing out the stack trace, which is the main thread's global execution context.

function foo(){
    function bar(){
        console.trace();
    }
    bar();
}
foo();

output:

console. trace
bar
foo
(anonymous)

This seems to be logical as JavaScript is a single-threaded language and there is only a single flow to execute all these functions. However, in the case that we are having some unpredictable or heavy tasks in the flow (for example making an API call), we do not want them to block the execution of the remaining codes (or else users might be staring at a frozen screen). This is where the asynchronous JavaScript comes in.

Thanks for reading this artical โœ’โ˜บ : )

Did you find this article valuable?

Support priyanka chaudhari by becoming a sponsor. Any amount is appreciated!

ย