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.
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.
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.
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.
Top comments (21)
Do you have links to some sources? To my knowledge different environments are handling this differently. I think Chrome uses only one thread while Node takes advantage of libuv. So the whole point would not be if the language is single threaded, but if its implementation is.
V8-Engine is used by chrome which does use libuv.
V8 apparently does not use libuv.
github.com/nodejs/help/issues/3124
tech.jotform.com/unraveling-the-ja...
Well it can use it and yes chrome has it's own event loop as well.
Yes, that's what Node does, but - as it seems - not Chrome. That's why I'm asking for sources
This is one of the resource that I used other resource would be YouTube and Node.js docs.
Don´t get me wrong, it is good to have more background information about how things work. But I was wondering, if this has any practical effect?
When a browser reads a page, it evaluates the content from top to bottom. Unless you do not add any infinite loops in Javascript, the evaluation of a page is finished within some milliseconds. HTML and JS are evaluated in the order they appear, but any code that has a long term effect (like events, setInterval, setTimeout etc...) are sorted out and forwarded to the event loop. So, in most cases it should not matter if the event loop runs in a separate thread or not.
You see it is as you say. The code gets executed within milliseconds but "any code that has a long term effect (like events, setInterval, setTimeout etc...)" this part is what runs on separate background threads. See the main thread does not handle setinterval, it is passed to the browser to be taken care of in background. When you make a async fetch request the dom does not stop responding, because the fetch request itself is being handle by browser and dom is being handled by the main thread. When I say background threads I am talking about this process happening. Hope it clears your doubt.
And again it has to do with the working of JavaScript, Node, Browsers, OS and every other component that makes a computer run, so it can get confusing very quickly. Especially when you learn about multithreading, multiprocessing, parallel and concurrent execution in Node.js.
Sure, in practice using different threads, makes things easier. Assume you have an inifinite loop in your script.
But my question was: Does this have any practical effect? After the main thread is finished it should not make any difference if the event loop was handeled by a separate thread or not.
And - by the way: even if the event loop runs in a different thread, this is still a single thread. So, it might not be blocked by the main thread, but if you put you infinite loop in an event, this will still block the whole site:
Well with infinite loops any system will get blocked because of deadlock. And in reality yes it does not matter normally, but when you are making applications using Node.js any other program or language for example slack, discord or a game. You need to look out for these things as when your application is going to make use of system resources, you would not want your program to use all the resources all by itself. Multi-threading and multi-processing give us this exact ability and knowing about the single threaded nature of JavaScript helps with that.
And what you are talking about is concurrency in a single thread. With the kind of powerful systems we have running tasks concurrently even when we have a single threads gives the illusion of fast parallel programming and makes it look like there is no need to worry about having multiple threads.
The way we achieve concurrency is by dumping async code onto background threads and letting the main thread execute without waiting for the results to come.
"Does this have any practical effect? After the main thread is finished it should not make any difference if the event loop was handled by a separate thread or not." Yes it matters cause if it it was not handle by background threads or if it was no handled concurrently the whole program would freeze. The whole point of background threads is to give you the ability of asynchronous programming.
My example code will freeze the whole application, even events are not handled anymore. Here is a running (or, not running) example in flems.io.
I did not know about this details of the V8-engine, so many thanks for the explanation. The problem itself is as old as graphical user interfaces are, and any solution has it´s drawbacks. If you run a full fledged multithreading system, event handling is done by the processor. This makes threads more reliable, but process communication is much more complex. So, I would see the V8-solution as kind of a compromize.
Knowing that the event loop CAN be blocked can be most helpful to prevent any trouble.
You are absolutely correct it doesn't have any thing to do practical working, but it is good to know the underlying working , because you never know what an interviewer might ask in interview 😂, ik you would say that's absurd why would someone would ask this , but in my last interview the interviewer asked me about multithreading and also asked to implement it (worker thread) and as an entry level developer and i couldn't, if i would came across this article before or find some relevant info , i would have responded him with this , and that would might leave him to ask anything further about this.
The example you provided was correct and event for async code it would do the same .
So yes the main thread will get blocked in this case but this blocking would only happen when the code written by a programmer is bad and I don't think anybody is going to write a infinite loop like this.
This was just a demonstration to showcase a total blockage. But it might easily happen that a laborous task is performed in an event routine, like database lookup, auto-complete, markdown-conversion etc. If you ever wondered, why your application acts so slow, this might be the answer.
Knowing about the single trheaded nature of the event loop might help you to find a better solution.
Yeah that is why things like that needs to be done with help of asynchronous code.
Web Workers should be compared with multi-thread rather than event loops I guess?
Not compared they are used to implement multi-threading.
youtu.be/MuwJJrfIfsU?si=an-FgGPP80... this video by Software Developers Diaries explains it well.