π Understanding Synchronous and Asynchronous Code in JavaScript
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
fsmoduleFunctional 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:
Node.js reads
a.txt.Waits until reading
a.txtfinishes.Then reads
b.txt.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.