"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Javascript is NOT single threaded!!

Javascript is NOT single threaded!!

Published on 2024-07-31
Browse:693

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.

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.

Javascript is NOT single threaded!!
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);
})

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.

Javascript is NOT single threaded!!

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.

Release Statement This article is reproduced at: https://dev.to/roshankbadola/javascript-is-not-single-threaded-3b9a?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3