JavaScript Internals (521 Qs)•Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)
Why is JavaScript treated as Single threaded
JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.
Practical Code Example
javascript
// Single-threaded: Only ONE call stack executes JavaScript code at any moment.
// Asynchronous operations are delegated to browser Web APIs / libuv thread pool:
console.log('1. Call Stack');
setTimeout(() => {
console.log('3. Web API Callback via Event Loop');
}, 0);
console.log('2. Call Stack Continues');
// Output: 1 -> 2 -> 3