#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Asynchronous JavaScript

Callbacks

A callback is a function you hand to another function so that it can be called later, usually when some work has finished. JavaScript runs your code on a single thread, so instead of stopping and waiting for a timer, a file read or a network response, it lets you say "when this is done, run this function". That function is the callback.

Functions are values you can pass around

Callbacks work because functions in JavaScript are ordinary values. You can store a function in a variable, put it in an array, or pass it as an argument, exactly like a number or a string. When you write setTimeout(sayHi, 1000), you are not calling sayHi yourself. You are giving it to setTimeout, which calls it after roughly one second.

Notice there are no brackets after sayHi. Writing sayHi() would run the function immediately and pass its return value instead, which is a very common beginner slip.

Synchronous and asynchronous callbacks

Not every callback is asynchronous. Array methods such as map, filter and forEach take callbacks too, but they call them right away, one item at a time, before the next line of your code runs. These are synchronous callbacks.

Asynchronous callbacks are different. Functions like setTimeout, addEventListener and Node's fs.readFile register your function and return immediately. The callback runs later, after the current code has finished and the event loop picks up the finished task.

console.log('1. start');

setTimeout(() => {
  console.log('3. timer finished');
}, 0);

[10, 20].forEach((n) => console.log('2. item', n));

console.log('2. end of script');

Even with a delay of zero, the timer message prints last. The timer callback waits in a queue until the main script is done, while the forEach callback runs in place.

The error-first convention in Node.js

Node.js core APIs follow a pattern for asynchronous callbacks: the first argument is an error (or null when things went well), and the remaining arguments carry the result. Checking the error before touching the data is your responsibility.

const fs = require('fs');

fs.readFile('notes.txt', 'utf8', (err, text) => {
  if (err) {
    console.error('Could not read file:', err.message);
    return;
  }
  console.log('File has', text.length, 'characters');
});

The return inside the error branch matters. Without it, the code below would still run with text set to undefined.

A mistake to watch for: expecting a return value

Beginners often try to get data out of an asynchronous callback by returning it:

  • They write let data = fs.readFile(..., (err, t) => t) and expect data to hold the file text.
  • In reality readFile returns undefined straight away, long before the callback runs.
  • The value returned from inside the callback goes back to Node's internals, not to your variable.

The fix is to do the work that needs the data inside the callback, or to call another function from there and pass the data along. Another subtle bug is calling a callback twice, for example once for an error and again for success, because a return was forgotten. Code that receives your callback usually assumes it fires exactly once.

Where callbacks start to hurt

One callback is easy to read. Trouble begins when step two depends on step one, step three on step two, and each step needs its own error check. The code drifts to the right and becomes hard to follow, which is the problem the next lesson looks at closely.

Quick recap

  • A callback is a function passed as an argument and called by the receiving function.
  • Pass the function itself, not the result of calling it.
  • Asynchronous callbacks run after the current script, so you cannot return their results directly.
  • In Node.js, always check the error argument first and return early when it is set.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course