How Does JavaScript Run?
🎯 Introduction
If you are new to frontend development, understanding how JavaScript runs will help you write more efficient code and avoid common asynchronous pitfalls. This article explains why JavaScript is single-threaded, how synchronous and asynchronous execution differ, how the call stack manages execution, and how the browser's event loop works. These concepts will help you debug and optimize your frontend applications.
🚦 Why Is JavaScript Single-Threaded?
JavaScript was designed as a single-threaded language. This means it has one execution thread and can execute only one task at a time.
There are several reasons for this design:
- Historical context: JavaScript was originally designed to make web pages respond to user actions. A single-threaded model is simpler and avoids common complexities of multithreaded programming, such as thread safety and resource contention.
- Safe DOM operations: A web page has one DOM (Document Object Model). Using a single thread prevents multiple threads from modifying it simultaneously and producing conflicting changes.
- Simpler development: Developers do not have to coordinate multiple execution threads, which reduces programming complexity.
🎭 Synchronous vs. Asynchronous Execution
JavaScript code can run synchronously or asynchronously.
- Synchronous: Statements execute in order. Each statement must finish before the next one starts, much like waiting in line to buy a ticket.
- Asynchronous: An operation can be handled in the background without blocking the next statement. You receive its result later, much like ordering food for delivery while continuing with other activities.
Synchronous Example
console.log('Start');
console.log('Processing');
console.log('End');
The output follows the order of the statements:
Start
Processing
End
Asynchronous Example
console.log('Start');
setTimeout(() => {
console.log('Timer callback');
}, 1000);
console.log('End');
The output is:
Start
End
Timer callback
Why does “End” appear first? Setting a timer is asynchronous and does not block the main thread. Its callback runs after the one-second delay.
🧱 What Is the Call Stack? How Does Code Execute Step by Step?
The call stack is the mechanism JavaScript uses to manage execution order.
When your code runs, the JavaScript engine pushes each function call onto the stack. When a function finishes, the engine pops it off and resumes the calling code.
An Example
function first() {
console.log('first starts');
second();
console.log('first ends');
}
function second() {
console.log('second runs');
}
first();
Execution proceeds as follows:
- Call
first()and pushfirstonto the stack. - Print
first starts. - Call
second()and pushsecondonto the stack. - Print
second runs. - Finish
second()and pop it off the stack. - Print
first ends. - Finish
first()and pop it off the stack.
The call stack keeps function execution in order.
🔄 The Browser Event Loop, Tasks, and Microtasks
JavaScript can execute only one task at a time, but many operations are asynchronous, including network requests, timers, and user clicks. Browsers use an event loop to coordinate asynchronous execution.
A Simple View of the Event Loop
The event loop continually coordinates the call stack and task queues:
- When the call stack is empty, the next queued task can execute on it.
- This allows asynchronous callbacks to run at the appropriate time.
Tasks (Macrotasks) and Microtasks
Browser scheduling distinguishes two kinds of work:
- Tasks (macrotasks): Work such as
setTimeoutandsetIntervalcallbacks and network request callbacks; UI rendering is coordinated with the event loop. - Microtasks: Work such as
Promise.thencallbacks andMutationObservercallbacks.
The event loop follows this sequence:
- Execute a task, such as the initial script.
- Run the microtask queue until it is empty.
- Update the page rendering when appropriate.
- Proceed to the next task.
An Example
console.log('script start');
setTimeout(() => {
console.log('setTimeout');
}, 0);
Promise.resolve()
.then(() => {
console.log('promise1');
})
.then(() => {
console.log('promise2');
});
console.log('script end');
Output:
script start
script end
promise1
promise2
setTimeout
Why does this happen?
- The script runs as a task and first prints
script start. setTimeoutschedules its callback as a task once the timer is ready.Promise.thenschedules its callback as a microtask.- The script prints
script end. - When the script task finishes and the call stack is empty, the microtasks run, printing
promise1and thenpromise2. - After the microtasks finish, the next task runs and prints
setTimeout.
❓ Knowledge Check
Q1: Why does JavaScript execute on a single thread? Its single-threaded design prevents conflicting DOM operations and simplifies the programming model.
Q2: How do asynchronous and synchronous execution differ? Synchronous code executes in order, blocking subsequent statements until it finishes. Asynchronous operations allow the main thread to continue and run callbacks when the work is ready.
Q3: What is the call stack? It is a stack that tracks active function calls and determines the order in which execution proceeds.
Q4: How do microtasks and tasks differ in the event loop? Tasks include scripts and timer callbacks. Microtasks include Promise callbacks and run before the next task.
🧪 Exercises
- Write code that demonstrates synchronous and asynchronous execution order.
console.log('Synchronous start');
setTimeout(() => {
console.log('Asynchronous timer');
}, 0);
console.log('Synchronous end');
Add a Promise callback to this example and observe the output order.
- Demonstrate the call stack with two functions, one calling the other, and log their execution order.
function foo() {
console.log('foo start');
bar();
console.log('foo end');
}
function bar() {
console.log('bar');
}
foo();
Try adding a third function and observe how the call stack changes.
🎉 You now understand JavaScript's single-threaded model, synchronous and asynchronous execution, the call stack, and the event loop! Use these fundamentals to write more reliable, efficient code.
