Table of contents
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.
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 โโบ : )