DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

Why JavaScript is Single-Threaded

JavaScript is one of the most popular programming languages used to build interactive websites. One important concept you will often hear is that JavaScript is single-threaded.

What Does Single-Threaded Mean?

A single-threaded language can execute only one task at a time.

JavaScript has:

One main thread
One call stack

This means tasks are executed one by one, in order.

Example:
console.log("Task 1");
console.log("Task 2");
console.log("Task 3");

Output:

Task 1
Task 2
Task 3

JavaScript does not run multiple lines at the same time.

Why is JavaScript Single-Threaded?

  1. Designed for Web Browsers

JavaScript was originally created to run inside web browsers.

According to W3Schools:
JavaScript is used to control the behavior of web pages.

It works with the DOM (Document Object Model).

If JavaScript had multiple threads:

Two threads could try to change the same element at the same time
This could create confusion and errors

So, JavaScript is single-threaded to keep things simple and safe.

  1. Easy to Learn and Use

Single-threaded design makes JavaScript:

Easier to understand
Easier to debug
Less complex

Developers don’t need to handle:

Thread management
Locks
Deadlocks

This is perfect for beginners.

  1. Uses a Call Stack

JavaScript uses a call stack to manage execution.

Example:

function first() {
  console.log("First");
}

function second() {
  first();
  console.log("Second");
}

second();

Enter fullscreen mode Exit fullscreen mode

Execution:

second() runs
first() runs
Then back to second()

Only one function runs at a time → single-threaded behavior

But JavaScript Can Handle Multiple Tasks

You might think:

“If JavaScript is single-threaded, how does it handle timers, APIs, etc.?”

Example:

console.log("Start");

setTimeout(() => {
  console.log("Hello after 2 seconds");
}, 2000);

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

Output:

Start
End
Hello after 2 seconds

This happens because of the Event Loop

Event Loop

JavaScript uses:

Call Stack
Web APIs
Callback Queue
Event Loop

According to MDN Web Docs:
The event loop allows JavaScript to perform non-blocking operations even though it is single-threaded.

So JavaScript can:

Start a task
Continue other work
Come back later

Top comments (0)