DEV Community

Mohsen Fallahnejad
Mohsen Fallahnejad

Posted on

JavaScript is Single-Threaded

🚦 What does "single-threaded" mean?

  • A thread is like a worker that can do tasks.
  • JavaScript has only one worker (one thread).
  • That worker can do only one thing at a time.

So if JS is running some code, it cannot start another piece of code at the same exact time on another thread.


🛑 Why does this matter?

  • If one task is slow (e.g. a heavy loop or waiting for a file), the single worker gets stuck.
  • This means your whole app (like a webpage) may freeze until the task finishes.

🍕 Analogy

Imagine a pizza chef in a small restaurant:

  • There’s only one chef (single thread).
  • If the chef is busy making a pizza, he cannot simultaneously make pasta.
  • To handle waiting times (like pizza baking in the oven), the chef can set a timer and move to the next order.
  • That timer is like callbacks, promises, or async/await.

⚡ How does JS still feel fast?

JavaScript uses the event loop + asynchronous operations:

  • Slow tasks (network calls, timers, etc.) are handed off to the browser / Node.js background helpers.
  • When they’re done, they say “Hey, I’m ready” and the single thread picks it up later.

This makes JS feel like it’s multitasking, even though only one thing runs at a time.


đź’» Code Example

console.log("Start");

setTimeout(() => {
  console.log("Async task done");
}, 0);

console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output

Start
End
Async task done
Enter fullscreen mode Exit fullscreen mode

👉 Even though the timeout is 0ms, the callback is delayed until the main thread finishes current tasks (Start and End).

This proves that JavaScript has only one main thread.


âś… Summary

JavaScript is single-threaded = one main worker runs tasks one after another.

With the event loop + async, it can still handle multiple tasks smoothly without blocking.

Originally published on: Bitlyst

Top comments (0)