DEV Community

Cover image for Javascript is not single threaded! 🤯 🤩

Javascript is not single threaded! 🤯 🤩

Gautam Vaja on February 24, 2024

Learn about the power of worker threads in JavaScript and how they can enhance your application's performance. What if I say you that JavaScript...
Collapse
 
joelbonetr profile image
JoelBonetR šŸ„‡ • Edited

I think you're mixing concepts here, it's a complex topic so no finger pointing, I've been there as well šŸ˜‚

  • Web Workers run in client side and are often used to handle PWA background processes such running cache-first strategies among others. These are the ones that can't access the DOM for security reasons despite running in the client side.

  • Worker threads run in Node runtime environment (server side) and are used to parallelize tasks such the ones you described in real world applications. These of course can't access the DOM but the reason is that it's a client API so it's not available in Node

You might be interested in Child Processes and clusters as well.

Last but not least, some concepts to take into account:

  • JavaScript is a language, it doesn't define a threading model and it's not necessarily single threaded.
  • The JS event loop implementation has historically been single threaded (its asynchronous nature makes it hard to get any benefit from multi-threading-it).
  • Most browsers have historically been single threaded (that might be the origin of the "myth"?), nowadays all of them are probably multi-threaded (chrome, chromium-based such Arc browser, Edge and so on are multi-threaded for sure).
  • Web Workers is not part of JavaScript, it is a browser feature which can be accessed through JavaScript.
  • Worker threads, child processes and clusters (among others) are not part of JavaScript, they are Node features which can be accessed through JavaScript.

important considerations

Aforementioned multi-threading features need to be picked with a grain of salt.
Was about to explain stuff but found this guy explaining it better than I could so here's the link instead

Best regards
šŸ™ƒ

Collapse
 
gajananbodhankar profile image
Gajanan Bodhankar

Very useful info, I read it and it helped me in an Interview. Thanks though!!