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");
Output:
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.
Top comments (0)