JavaScript Single thread

nameismani

Manikandan K

Posted on February 14, 2024

JavaScript Single thread

JavaScript is a synchronous, blocking, single-threaded language.

Synchronous

  • Synchronously means that the programmer is executed line by line.
  • In JavaScript, synchronous is a behavior where tasks are executed one after another in a top-down approach.
  • That means each task must wait for the previous one's completion.
  • In other words, synchronous code executes sequentially, and if a task takes a long time to complete, it can block the execution of subsequent tasks.

Blocking

  • It refers to blocking further or next functions or operations until the current task is finished.**

Single thread
You know how, when you're trying to juggle multiple tasks at work or at home, you can only focus on one thing at a time? You might be writing an email, and you can't start another task until you hit send. 

  • That's how JavaScript works too—it can only do one thing at a time. 
  • If it's busy doing something like fetching data from a server or animating a web-page, it can't do anything else until it's finished.
console.log("Task Start");

function someFunction() {
  console.log("First Execution");
  console.log("Second Execution");
}

someFunction();

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

Output:

Image description

summary
when a function like someFunction() is executed synchronously, it means that the JavaScript code will run step by step, in order.
So, when someFunction() is called, the program won't move on to the next line (console.log("Task End")) until someFunction() finishes running all its code.

But how multi thread / Non-Blocking?

JavaScript nature behavior is single thread. But Yes, it's possible to achieve concurrency in JavaScript using techniques like Web Workers in web browsers and Worker Threads in Node.js. These mechanisms allow you to run JavaScript code in separate threads, enabling concurrent execution and improving performance for certain tasks. While JavaScript itself remains single-threaded in its core, these technologies provide a way to leverage multi-threading capabilities in JavaScript environments.

💖 💪 🙅 🚩
nameismani
Manikandan K

Posted on February 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Simplified: Javascript V8 engine ✨
javascript Simplified: Javascript V8 engine ✨

October 1, 2024

What is JSON?
javascript What is JSON?

September 20, 2024

Introduction to Node.js
javascript Introduction to Node.js

August 1, 2024

JavaScript on the Server: Node.js
javascript JavaScript on the Server: Node.js

July 28, 2024