DEV Community

Cover image for Understanding Synchronous and Asynchronous JavaScript
Annapoorani Kadhiravan
Annapoorani Kadhiravan

Posted on

Understanding Synchronous and Asynchronous JavaScript


JavaScript is a single-threaded language, meaning it executes one task at a time. However, modern applications frequently perform tasks that take time, such as:

  • Fetching data from APIs
  • Reading files
  • Uploading images
  • Waiting for user actions
  • Accessing databases

To handle these operations efficiently, JavaScript uses two execution models:

  1. Synchronous Execution
  2. Asynchronous Execution

What is Synchronous JavaScript?

In synchronous programming, code executes line by line, and each statement waits for the previous statement to finish.

Definition

Synchronous means one task at a time, in sequence.


Example

console.log("Task 1");

console.log("Task 2");

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

Output

Task 1
Task 2
Task 3
Enter fullscreen mode Exit fullscreen mode

How it Works

Task 1
 ↓
Task 2
 ↓
Task 3
Enter fullscreen mode Exit fullscreen mode

Each task waits for the previous one to complete.


Real-Life Example: ATM Queue

Imagine three people standing in front of an ATM.

Person 1
 ↓
Person 2
 ↓
Person 3
Enter fullscreen mode Exit fullscreen mode

Person 2 cannot use the ATM until Person 1 finishes.

Similarly, synchronous JavaScript processes one operation at a time.


Another Example

function first() {
    console.log("First Function");
}

function second() {
    console.log("Second Function");
}

first();
second();
Enter fullscreen mode Exit fullscreen mode

Output

First Function
Second Function
Enter fullscreen mode Exit fullscreen mode

Problem with Synchronous Execution

Suppose one operation takes a long time.

console.log("Start");

for(let i = 0; i < 10000000000; i++) {

}

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

The program becomes blocked until the loop finishes.


Execution Flow

Start
 ↓
Long Process
 ↓
End
Enter fullscreen mode Exit fullscreen mode

Nothing else can happen during the long process.


What is Asynchronous JavaScript?

Asynchronous programming allows JavaScript to start a task and continue executing other tasks without waiting for that task to finish.

Definition

Asynchronous means tasks can happen independently without blocking the program.


Example

console.log("Start");

setTimeout(() => {
    console.log("Timer Finished");
}, 3000);

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

Output

Start
End
Timer Finished
Enter fullscreen mode Exit fullscreen mode

Execution Flow

Start
 ↓
setTimeout() starts
 ↓
Continue execution
 ↓
End
 ↓
Timer completes
 ↓
Timer Finished
Enter fullscreen mode Exit fullscreen mode

JavaScript doesn't wait for the timer to finish.


Real-Life Example: Restaurant

Imagine ordering food in a restaurant.

Synchronous Approach

Order food
Wait 20 minutes
Eat food
Pay bill
Enter fullscreen mode Exit fullscreen mode

Nothing else happens while waiting.


Asynchronous Approach

Order food
Talk to friends
Check phone
Food arrives
Eat
Enter fullscreen mode Exit fullscreen mode

You continue doing other tasks while waiting.

This is how asynchronous programming works.


Why Do We Need Asynchronous Programming?

Many operations take time:

  • API requests
  • Database queries
  • File reading
  • Uploading images
  • Payment processing
  • Network communication

Without asynchronous programming, applications would freeze.


Example: API Request

console.log("Fetching data...");

fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => console.log(data));

console.log("Program continues...");
Enter fullscreen mode Exit fullscreen mode

Output

Fetching data...
Program continues...
[User data]
Enter fullscreen mode Exit fullscreen mode

The application continues running while data is being fetched.


Synchronous vs Asynchronous

Synchronous Asynchronous
Executes line by line Doesn't wait for tasks to finish
Blocking Non-blocking
Slow for long operations Efficient
Simple to understand More complex
Tasks run sequentially Tasks run independently
One task at a time Multiple operations can overlap

Visual Comparison

Synchronous

Task 1
 ↓
Task 2
 ↓
Task 3
 ↓
Task 4
Enter fullscreen mode Exit fullscreen mode

Asynchronous

Task 1
 ↓
Task 2 starts
 ↓
Task 3 executes immediately
 ↓
Task 4 executes
 ↓
Task 2 completes later
Enter fullscreen mode Exit fullscreen mode

setTimeout() Example

console.log("1");

setTimeout(() => {
    console.log("2");
}, 2000);

console.log("3");
Enter fullscreen mode Exit fullscreen mode

Output

1
3
2
Enter fullscreen mode Exit fullscreen mode

Why?

JavaScript sends setTimeout() to the browser's Web API and continues executing the next line.


Real-Life Example: Washing Machine

Synchronous

Start washing
Wait
Wait
Wait
Washing completes
Cook dinner
Enter fullscreen mode Exit fullscreen mode

Asynchronous

Start washing
Cook dinner
Watch TV
Read book
Washing completes
Enter fullscreen mode Exit fullscreen mode

Multiple activities happen simultaneously.


Ways to Handle Asynchronous Operations

JavaScript provides three main approaches:

1. Callbacks

2. Promises

3. Async/Await


1. Callback

A callback function executes after another task completes.

function fetchData(callback) {

    setTimeout(() => {

        callback();

    }, 2000);
}

fetchData(() => {

    console.log("Data received");

});
Enter fullscreen mode Exit fullscreen mode

Output

Data received
Enter fullscreen mode Exit fullscreen mode

Real-Life Example

Food delivery:

Order food
↓
Food prepared
↓
Delivery boy calls you
Enter fullscreen mode Exit fullscreen mode

The call is like a callback function.


2. Promise

A Promise represents a value that will be available in the future.

let promise = new Promise((resolve, reject) => {

    resolve("Success");

});

promise.then(result => {

    console.log(result);

});
Enter fullscreen mode Exit fullscreen mode

Output

Success
Enter fullscreen mode Exit fullscreen mode

Promise States

Pending
   ↓
Resolved
or
Rejected
Enter fullscreen mode Exit fullscreen mode

Real-Life Example

Online Shopping

Place order
↓
Pending
↓
Delivered (Resolved)

or

Cancelled (Rejected)
Enter fullscreen mode Exit fullscreen mode

3. Async/Await

Introduced in ES2017.

It makes asynchronous code look like synchronous code.

async function getMessage() {

    return "Hello";

}

getMessage().then(console.log);
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Enter fullscreen mode Exit fullscreen mode

Example with await

async function fetchUser() {

    let response = await fetch(
        "https://jsonplaceholder.typicode.com/users/1"
    );

    let data = await response.json();

    console.log(data);

}

fetchUser();
Enter fullscreen mode Exit fullscreen mode

Real-Life Example

Ordering Pizza

Place order
↓
Wait for preparation
↓
Receive pizza
Enter fullscreen mode Exit fullscreen mode

await tells JavaScript:

"Pause this function until the result is ready, but don't block the rest of the program."


Behind the Scenes

JavaScript uses:

Call Stack

Stores function execution.

main()
 ↓
function1()
 ↓
function2()
Enter fullscreen mode Exit fullscreen mode

Web APIs

Handle asynchronous tasks like:

  • setTimeout()
  • fetch()
  • DOM events

Callback Queue

Stores completed asynchronous tasks.

Completed Task
 ↓
Waiting Queue
Enter fullscreen mode Exit fullscreen mode

Event Loop

Checks whether the Call Stack is empty and moves tasks from the queue into the stack.

Queue
 ↓
Event Loop
 ↓
Call Stack
Enter fullscreen mode Exit fullscreen mode

Complete Example

console.log("Start");

setTimeout(() => {

    console.log("Inside Timer");

}, 2000);

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

Execution

Call Stack

console.log("Start")
Enter fullscreen mode Exit fullscreen mode

Output:

Start
Enter fullscreen mode Exit fullscreen mode

setTimeout()

Moves to Web API

Timer starts
Enter fullscreen mode Exit fullscreen mode

Next Statement

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

Output:

End
Enter fullscreen mode Exit fullscreen mode

Timer Finishes

Moves to Callback Queue

Inside Timer
Enter fullscreen mode Exit fullscreen mode

Event Loop

Pushes callback into Call Stack

Output:

Inside Timer
Enter fullscreen mode Exit fullscreen mode

Summary

Feature Synchronous Asynchronous
Execution One after another Independent
Waiting Yes No
Blocking Blocking Non-blocking
Speed Slower for heavy tasks Faster and efficient
Complexity Simple More advanced
Examples Mathematical calculations API calls, file uploads, timers

Key Takeaways

  • Synchronous JavaScript executes code one line at a time.
  • Asynchronous JavaScript allows other tasks to continue while waiting.
  • JavaScript is single-threaded but achieves asynchronous behavior through:

    • Web APIs
    • Callback Queue
    • Event Loop
  • Asynchronous programming is implemented using:

    • Callbacks
    • Promises
    • Async/Await

Synchronous programming is like standing in a queue and waiting for your turn.

Asynchronous programming is like placing an order online and continuing with your day while the order is being prepared.

Understanding synchronous and asynchronous execution is fundamental to mastering Promises, Async/Await, APIs, Node.js, React, and modern JavaScript development.

References :
https://www.geeksforgeeks.org/javascript/synchronous-and-asynchronous-in-javascript/
https://www.browserstack.com/guide/synchronous-vs-asynchronous-in-javascript

Top comments (0)