Skip to main content

Command Palette

Search for a command to run...

🌐 Understanding Synchronous and Asynchronous Code in JavaScript

Published
β€’2 min readβ€’View as Markdown

When you're starting out with JavaScript, one of the most important things to understand is how your code runs β€” synchronously or asynchronously. This can greatly affect performance, especially in web development or when working with files and APIs.

In this blog, we’ll explore:

  • What is synchronous vs asynchronous code?

  • Examples using Node.js and the fs module

  • Functional arguments and callbacks


πŸ” Synchronous Code

Synchronous code is executed line by line, and each operation waits for the previous one to complete before it moves forward.

This is simple to understand but can become problematic if a task takes a long time to finish β€” it blocks everything else until it's done.

βœ… Example: Synchronous File Reading

jsCopyEditconst fs = require("fs");

const contents = fs.readFileSync("a.txt", "utf-8");
const contents1 = fs.readFileSync("b.txt", "utf-8");

console.log(contents);
console.log(contents1);

🧠 How it works:

  1. Node.js reads a.txt.

  2. Waits until reading a.txt finishes.

  3. Then reads b.txt.

  4. Only after both are read does it log the contents.

βœ… Simple to debug
β›” Blocks the thread (bad for performance on slow tasks)


πŸ”„ Asynchronous Code

Asynchronous code does not wait. Instead, tasks like reading a file are kicked off, and the program keeps going. When the task finishes, it calls a function (called a callback) to handle the result.

βœ… Example: Asynchronous File Reading

jsCopyEditconst fs = require("fs");

fs.readFile("a.txt", "utf-8", function (err, contents) {
    console.log(contents);
});

fs.readFile("b.txt", "utf-8", function (err, contents) {
    console.log(contents);
});

fs.readFile("a.txt", "utf-8", function (err, contents) {
    console.log(contents);
});

🧠 How it works:

  • All file reads are started at the same time.

  • The program does not wait for one to finish before starting the next.

  • When each read is complete, the associated callback runs.

βœ… Fast and non-blocking
β›” Harder to debug due to out-of-order execution


πŸ”§ Functional Arguments

In JavaScript, functions can be passed as arguments to other functions. These are known as functional arguments.

βœ… Example:

jsCopyEditfunction greet(name) {
    console.log("Hello, " + name);
}

function processUserInput(callback) {
    const name = "Alice";
    callback(name);
}

processUserInput(greet);

Here, the greet function is passed to processUserInput and executed inside it.

More from this blog

JavaScript

6 posts