javascriptnode.jssingle-threaded

Is JavaScript single threaded?


As it is obvious that nodeJs is single-threaded. But JavaScript as a language is also single-threaded?


Solution

  • Javascript isn't inherently single-threaded or multi-threaded as a language. There are Javsacript environments that don't offer Javascript threads and environments that do offer Javascript threads. The language itself doesn't specify single-threadedness or multi-threadedness. Instead, it's up to the environment whether it wants to make threads of Javascript available.

    So, to your specific question:

    Is JavaScript single threaded?

    No. It's not specifically single threaded or multiple threaded. The language specification doesn't require either. The threading of Javascript is up to the run-time environment to implement. It so happens that both the browser and node.js started out without Javascript threads and an event-driven architecture which led to this notion that there are no threads in a Javascript environment, but there ARE. They now both offer Javascript threads (WebWorkers in the browser and WorkerThreads in node.js).

    The Javascript specification offers some features that are useful in multi-threaded environments such as SharedArrayBuffer objects and Atomics and environments that offer threading provide additional libraries. So, the current language specification recognizes some of the needs of multi-threading and provides some tools for it, though there is no specific requirement that a Javascript runtime has or doesn't have threads. It's up to the run-time whether they want to offer that capability to run multiple Javascript threads of execution in parallel or not.