惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
量子位
Y
Y Combinator Blog
大猫的无限游戏
大猫的无限游戏
B
Blog
U
Unit 42
C
Check Point Blog
I
InfoQ
aimingoo的专栏
aimingoo的专栏
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
H
Hackread – Cybersecurity News, Data Breaches, AI and More
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
云风的 BLOG
云风的 BLOG
宝玉的分享
宝玉的分享
爱范儿
爱范儿

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Callbacks in JavaScript: Why They Exist
SATYA SOOTAR · 2026-04-27 · via DEV Community

Hello readers 👋, welcome to the 14th blog in this JavaScript series!

Today, let’s talk about something that’s at the heart of asynchronous JavaScript: callback functions. If you’ve ever worked with async code, you’ve probably used callbacks, maybe without even realizing it.

Callbacks can seem a bit abstract at first, but once you understand why they exist and how they work, they become a powerful tool in your coding toolkit. Let’s break it down step by step.

What is a callback function?

In JavaScript, a callback function is simply a function that is passed as an argument to another function and is executed after some operation has been completed. In other words, it’s a function that “calls back” when something is done.

Here’s a basic example:

function greet(name, callback) {
  console.log(`Hello, ${name}!`);
  callback();
}

function sayGoodbye() {
  console.log("Goodbye!");
}

greet("Satya", sayGoodbye);

Enter fullscreen mode Exit fullscreen mode

In this example, sayGoodbye is a callback function. It’s passed to greet and called after the greeting is printed.

Why do callbacks exist?

Callbacks are especially important in asynchronous programming. JavaScript is single-threaded, meaning it can only do one thing at a time. But many operations like fetching data from a server, reading a file, or waiting for a user to click a button take time. Instead of blocking the entire program, JavaScript uses callbacks to say, “Hey, when this slow operation is done, run this function.”

Example: setTimeout

console.log("Start");

setTimeout(function() {
  console.log("This runs after 2 seconds");
}, 2000);

console.log("End");

Enter fullscreen mode Exit fullscreen mode

Here, the anonymous function inside setTimeout is a callback. It runs after 2 seconds, but the rest of the code doesn’t wait it keeps executing.

Passing functions as arguments

In JavaScript, functions are first-class objects. This means you can pass them around just like any other value numbers, strings, or objects.

function processUserInput(callback) {
  const name = prompt("Please enter your name:");
  callback(name);
}

processUserInput(function(name) {
  alert(`Hello, ${name}!`);
});

Enter fullscreen mode Exit fullscreen mode

Here, the function processUserInput takes another function as an argument and calls it with the user’s input.

Common use cases for callbacks

1. Event handling

document.getElementById("myButton").addEventListener("click", function() {
  console.log("Button clicked!");
});

Enter fullscreen mode Exit fullscreen mode

The function inside addEventListener is a callback. It runs when the button is clicked.

2. Array methods

Many array methods, like map, filter, and forEach, use callbacks:

const numbers = [1, 2, 3];
const doubled = numbers.map(function(num) {
  return num * 2;
});
console.log(doubled); // [2, 4, 6]

Enter fullscreen mode Exit fullscreen mode

3. Asynchronous operations

Callbacks are everywhere in async code, like reading files or making HTTP requests:

const fs = require('fs');
fs.readFile('example.txt', 'utf8', function(err, data) {
  if (err) throw err;
  console.log(data);
});

Enter fullscreen mode Exit fullscreen mode

The problem with callback nesting

While callbacks are powerful, they can lead to a situation called callback hell or the “pyramid of doom.” This happens when you have multiple async operations that depend on each other, leading to deeply nested callbacks:

getUser(userId, function(user) {
  getPosts(user.id, function(posts) {
    getComments(posts[0].id, function(comments) {
      console.log(comments);
    });
  });
});

Enter fullscreen mode Exit fullscreen mode

This code is hard to read and maintain. Modern JavaScript provides solutions like Promises and async/await to handle this more elegantly.

Conclusion

Callbacks are a fundamental concept in JavaScript, especially for handling asynchronous operations. They allow you to write code that doesn’t block the main thread and can respond to events or data as it becomes available.

To recap:

  • A callback is a function passed as an argument to another function.
  • They are essential for async programming in JavaScript.
  • You can pass functions as arguments because functions are first-class objects.
  • Callbacks are used in event handling, array methods, and async operations.
  • Deeply nested callbacks can become hard to manage (callback hell).

If you’re new to JavaScript, understanding callbacks will give you a solid foundation for working with async code and preparing for more advanced topics like Promises and async/await.


Hope you found this helpful! If you spot any mistakes or have suggestions, let me know. You can find me on LinkedIn and X, where I post more about web development.