WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Basic · question 13 of 100

What are callbacks in Node.js, and how do they help in asynchronous programming?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

Callbacks are a programming pattern that enables a function to receive another function as an argument. In Node.js, they are frequently used to handle asynchronous operations, providing a mechanism to define how the program behaves once a particular task is complete. This enables non-blocking, concurrency, and efficient code execution while managing multiple tasks simultaneously without pausing or hanging the application.

In Node.js, a callback is usually represented as the last argument in a function that is being called. This callback function is invoked after the completion of the main function’s operation, providing the results (or errors) to the callback function.

Let’s consider a simple example to demonstrate callbacks:

function greeting(name, callback) {
  let message = `Hello, ${name}`;
  callback(null, message);
}

function displayMessage(error, message) {
  if (error) {
    console.error("There was an error:", error);
  } else {
    console.log(message);
  }
}

greeting("Alice", displayMessage);

In this example, the ‘greeting‘ function accepts a name and a callback function as its arguments. The ‘displayMessage‘ function is passed as a callback and includes both error and message parameters. When the ‘greeting‘ function finishes forming its message, it calls ‘displayMessage‘, which logs the message to the console or prints an error if it exists.

In the case of asynchronous programming, callbacks help manage the control flow while waiting for the asynchronous operation to complete. For a practical example, let’s examine a file read operation using Node.js’s filesystem ‘fs‘ module.

const fs = require('fs');

function readFileCallback(error, data) {
  if (error) {
    console.error("An error occurred:", error);
  } else {
    console.log("Content of the file:", data.toString());
  }
}

fs.readFile("example.txt", "utf8", readFileCallback);

In this example, the ‘fs.readFile‘ function reads the content of the "example.txt" file. Since this operation can take an indeterminate amount of time (depending on the file’s size), the function runs asynchronously. The ‘readFileCallback‘ function is provided as the callback argument, and once the file has been read, it is executed with either an error if it occurred or the data read from the file.

In summary, callbacks are an essential pattern in Node.js for managing asynchronous operations. By passing a callback function to another function, we can define how the application behaves once the operation is complete while avoiding blocking the application from processing other tasks. However, callbacks can lead to a "callback hell" if used excessively or nested too deeply, which is why modern JavaScript has introduced Promises and async/await syntax to handle asynchronous code more efficiently and with improved readability.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics