Jump to content

Featured Replies

Posted

You are reading Part 15 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]

Introduction

JavaScript is a single-threaded language, meaning it executes one command at a time in a specific order. Understanding the difference between synchronous (blocking) and asynchronous (non-blocking) operations is crucial for writing efficient and responsive applications.

Understanding synchronous vs asynchronous programming is essential for optimizing performance in JavaScript applications. Synchronous code is easier to understand but can block execution, while asynchronous programming improves responsiveness and efficiency. Mastering callbacks, promises, and async/await helps in writing better asynchronous code, avoiding blocking operations, and creating smooth user experiences.

1. Synchronous (Blocking) Operations

In synchronous programming, operations execute sequentially. Each statement waits for the previous one to complete before executing.

Example of Synchronous Code:

console.log("Start");

for (let i = 0; i < 5; i++) {
    console.log("Processing: ", i);
}

console.log("End");

Output:

Start
Processing: 0
Processing: 1
Processing: 2
Processing: 3
Processing: 4
End
  • The execution follows a strict order.

  • If a task takes too long (e.g., a large loop or file read), the entire script is blocked until it finishes.

2. Asynchronous (Non-Blocking) Operations

In asynchronous programming, tasks do not wait for others to complete. Instead, they run independently, allowing the program to continue execution.

Example of Asynchronous Code:

console.log("Start");

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

console.log("End");

Output:

Start
End
Delayed Execution (after 2 seconds)
  • The setTimeout() function schedules an operation without blocking the rest of the script.

  • This improves performance, especially for time-consuming tasks like fetching data from a server.

3. JavaScript Event Loop & Call Stack

JavaScript handles asynchronous operations using the event loop.

How it Works:

  1. The Call Stack executes functions in order.

  2. If an asynchronous task (e.g., setTimeout(), fetch()) is encountered, it is sent to the Web API.

  3. Once the task completes, it moves to the Callback Queue.

  4. The Event Loop checks if the Call Stack is empty and then moves the completed task to execution.

Visual Representation:

Call Stack      →    Web API    →    Callback Queue   →    Event Loop

4. Common Asynchronous Techniques

Using Callbacks

A function that is passed as an argument to another function and executed later.

function fetchData(callback) {
    setTimeout(() => {
        callback("Data loaded");
    }, 2000);
}
fetchData((data) => console.log(data));

Using Promises

A modern approach to handling async operations.

let fetchData = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Data loaded");
    }, 2000);
});

fetchData.then(data => console.log(data));

Using Async/Await

A cleaner, more readable syntax for promises.

async function getData() {
    let data = await fetchData;
    console.log(data);
}
getData();

5. When to Use Synchronous vs Asynchronous?

Scenario

Synchronous

Asynchronous

Simple calculations

Fetching API data

Reading a local file

Processing user input

Heavy computation

(but use workers)

You are reading Part 15 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]

  • Views 30
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.