Single-threaded nature of JavaScript

JavaScript is a single-threaded language that executes code line by line, one command at a time.

To understand why single-threaded nature we need to know some more things.

  1. Cores - A CPU is divided into multiple units, and those units are known as cores.

  2. Context Switching - Context Switching is the process where the CPU switches between different tasks. Tasks that are not single-threaded can be divided into smaller parts and executed by multiple cores simultaneously, reducing the load on any single core.

  3. Code splitting in cores - Languages like C++ can use code splitting to take advantage of multiple cores. This means one program can be divided into smaller tasks that are executed simultaneously on different cores which improves performance.

How it works in languages like C++

#include <iostream>
using namespace std;

void printHello() {
    cout << "Hello from function!" << endl;
}

int main() {
    cout << "Hello World" << endl;
    printHello();
    return 0;
}

The C++ program can be designed to use code splitting to distribute tasks across multiple CPU cores, enabling simultaneous execution. This approach enhances performance through parallel processing, allowing faster execution by simultaneously handling several independent parts or units of the program.

In this context, "task" refers to a specific part or unit of the program that can be executed independently.

How it works in languages like JavaScript

// index.js
const num1 = 10;
const num2 = 20;
const result = num1 + num2;
console.log(result);

JavaScript programs run on a single core and cannot split tasks into multiple cores. This can make them slower to run compared to languages that can use multiple cores for faster processing.

A JavaScript program is executed on a single thread, which is why JavaScript is considered single-threaded.

However, JavaScript can utilize all available cores using the Cluster module, which we'll see later.