Javascript is NOT single threaded!!

Roshan Kumar Badola - Jul 22 - - Dev Community

NO! you have not learned wrong that JavaScript is a single threaded language. It is a single-threaded language it has access to a single main thread to execute the code. So when we talk about synchronous programming, we are talking about this lone thread doing all the heavy lifting and executing our code.
Image description

But in reality V8 engine and Node.js use a c library called libuv to get access to six extra threads. Two of these are used for doing garbage collection and the rest are used for doing background tasks like asynchronous programming.
Do keep in mind that browsers are a completely different environment then Node.js and and handle this process in a different way.

Yes. When we say that code is asynchronous or non-blocking what really happens is the async code is passed to these extra threads with the callback and the main thread keeps on doing its work without blocking the rest of the code.

Image description
When the async code is finished, the callback function is pushed into the event queue with either error or the required data. Then the event loop pushes it into the call stack and boom we get our result, to understand this with some code. Let's look at the readfile method of fs module.

fs.readFile("demo.text","utf8",(err,data)=>{
    if(error){       
        return error
    }
    console.log("output",data);
})
Enter fullscreen mode Exit fullscreen mode

In the code above the readfile method is passed to the background threads. The reading to happens in the background, and when that gets finished the callback is pushed into the event queue with either error or data.

Image description

Once in callstack the callback is executed and we are left with either error or the data as output.
Thanks for reading I hope I was able to explain about the single threaded means in Javascript.

TLDR : Yes JavaScript is a single threaded and synchronous programming language but we can achieve performance like a multi-threaded language by utilizing background threads for asynchronous programming.

. .
Terabox Video Player