It's not multithreaded with one minor exception. Let's talk about that exception later. First, lets see why things can happen in parallel but not multithreaded.
Waiting for I/O
When you send something over the network, for example, making a http request, waiting for a http response to complete or waiting for mysql to respond your software is not doing anything.
So, how can the network work if your software is not doing anything? (sorry if this is obvious but pointing out the obvious is usually what makes it obvious).
Some things happen outside the CPU
First, most of the network is outside your CPU. You have your network card buffering data going out and coming in. You have the electrons in the network cable or photons in space/air vibrating according to the signal sent by networking equipment. You have your router, your ISP, the server on the other side of the planet etc.
All the above needs to be processed in order for your http request to return data. In most languages, while all the above is happening, your code will not be doing anything.
Not so in javascript. When an I/O request is made, instead of waiting for the data to return the interpreter will simply register a callback you supply to execute when the data finally gets here. Now that that's done, other code can execute. Maybe some other data requested earlier is now here and that callback can be executed. Maybe a setTimeout
has expired and it's time to call that callback.
So multiple things can happen in parallel, most of it outside your process, a lot of it outside your CPU, some of it on another machine which may even be on the other side of the planet. While that's going on, javascript allows you to run some code.
The exception: disk I/O
The exception to this is disk I/O. At the lowest level (actually, next-to-lowest) C exposes only synchronous functions like fread()
, fwrite()
for I/O. Reading network packets are also technically synchronous. The difference is that the network doesn't respond immediately so the networking code has lots of time to spare waiting for packets. It is in between these reads and writes that javascript runs your code. But the filesystem will happily tell you that data is immediately available. So, unlike the networking code, the code reading from disk will spend most of its time being busy.
There are several work-arounds to this. Some OS even have asynchronous API to read from disk. The node.js developers have decided to handle this situation by spawning another thread to do disk I/O. So for disk I/O it is parallel because it's multithreaded.