💻 Programming

Callback

Callback

A function passed as an argument to another function and called later. The basis of asynchronous programming.

📖 Detailed Explanation

A callback is a function that is passed as an argument to another function and is "called back" at a specific point in time. It is a core pattern in languages that treat functions as first-class citizens, and it is widely used in most modern programming languages such as JavaScript, Python, and C++.

The most important use of callbacks is asynchronous programming. When performing time-consuming operations such as reading files, making network requests, or running timers, a program can register a callback function and continue performing other tasks instead of stopping to wait for the result. When the operation completes, the callback function is called automatically to handle the result.

Callbacks are also used synchronously. They are passed as the function that processes each element in higher-order functions such as an array's map, filter, and forEach. Event handlers are also a representative example of synchronous callbacks: a function to be executed on a user click or keyboard input is registered in advance.

However, nesting asynchronous callbacks causes a readability problem known as "Callback Hell." Patterns such as Promise and async/await emerged to solve this, but callbacks are still used as a core concept in event listeners, library APIs, Node.js core modules, and more.

💻 Code Example

// 1. 기본 콜백 패턴 - 동기 콜백
function greet(name, callback) {
    console.log(`안녕하세요, ${name}님!`);
    callback();  // 전달받은 함수를 호출
}

greet('홍길동', function() {
    console.log('환영합니다!');
});
// 출력: 안녕하세요, 홍길동님!
// 출력: 환영합니다!


// 2. 비동기 콜백 - setTimeout, 파일 읽기
console.log('1. 시작');

setTimeout(function() {
    console.log('2. 2초 후 실행됨');
}, 2000);

console.log('3. setTimeout 등록 후 바로 실행');
// 출력 순서: 1 → 3 → 2 (2초 후)


// 3. 에러 처리 패턴 (Node.js 스타일)
function fetchData(userId, callback) {
    // 비동기 작업 시뮬레이션
    setTimeout(() => {
        if (userId <= 0) {
            callback(new Error('유효하지 않은 사용자 ID'), null);
            return;
        }
        const user = { id: userId, name: '김철수' };
        callback(null, user);  // 첫 번째 인자가 에러, 두 번째가 결과
    }, 1000);
}

fetchData(1, (error, user) => {
    if (error) {
        console.error('오류:', error.message);
        return;
    }
    console.log('사용자:', user.name);
});


// 4. 배열 고차 함수에서의 콜백
const numbers = [1, 2, 3, 4, 5];

// map: 각 요소를 변환
const doubled = numbers.map(n => n * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

// filter: 조건에 맞는 요소만 선택
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);  // [2, 4]

// reduce: 누적 계산
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum);  // 15


// 5. 이벤트 리스너 콜백 (브라우저 환경)
document.getElementById('myButton').addEventListener('click', function(event) {
    console.log('버튼이 클릭되었습니다!');
    console.log('클릭 위치:', event.clientX, event.clientY);
});

🗣️ Say It Like This in Practice

💬 In a Meeting
"This API is asynchronous, so we have to receive the result through a callback. But if callbacks are nested three or more levels deep, readability suffers, so I think it would be better to wrap it in a Promise or refactor it with async/await."
💬 In an Interview
"A callback is a pattern where you pass a function as an argument and call it later. It's often used in asynchronous processing, but if nesting gets deep, callback hell can occur. Promise was introduced to solve this, and async/await was added in ES2017, making it possible to write asynchronous code like synchronous code."
💬 In a code review
"The error handling is missing in this callback. Following the Node.js convention, take error as the first parameter, run the logic after a null check. Otherwise, you need to wrap it in try-catch to catch the exception."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Avoiding Callback Hell

If you nest callbacks three or more levels deep, the code's indentation becomes deep in a pyramid shape. Use Promise or async/await, or separate the callback functions out, to improve readability.

❌
Missing Error Handling

If you ignore the error parameter in an asynchronous callback, errors are silently ignored. Follow the Node.js-style error-first callback pattern, and always check the error first.

❌
The this Binding Problem

If you pass a callback as a regular function, this may be bound differently than expected. Use an arrow function or bind explicitly with .bind(this).

✅
Proper Use of Callbacks

Callbacks are suitable for event listeners and simple asynchronous operations. Use Promise or async/await for complex asynchronous flows, and choose the pattern that fits each situation.

🔗 Related Terms

📚 Learn More