Callback
ELI5 — The Vibe Check
A callback is just a function you pass to another function, saying 'when you're done, call this.' Like giving someone your phone number and saying 'text me when the pizza is ready.' Callbacks were how JavaScript handled async stuff before Promises, which led to the legendary 'callback hell' of deeply nested spaghetti code.
Real Talk
A callback is a function passed as an argument to another function, to be invoked at a later time (synchronously or asynchronously). They are foundational to JavaScript's asynchronous model. Nesting callbacks leads to 'callback hell' (pyramid of doom). Promises and async/await were introduced to address this readability problem.
Show Me The Code
// Simple callback
function greet(name, callback) {
console.log('Hello, ' + name)
callback()
}
greet('World', () => console.log('Done!'))
// Callback hell (avoid this)
getUser(id, function(user) {
getPosts(user.id, function(posts) {
getComments(posts[0].id, function(comments) {
// 😱 pyramid of doom
})
})
})
When You'll Hear This
Array methods like .map() and .filter() take callbacks.,Callback hell is why Promises were invented.,Event listeners use callbacks: element.addEventListener('click', callback).
Related Terms
Async/Await
Async/await is syntactic sugar that makes Promises look like normal, readable code. Instead of chaining .then().then().
Closure
A closure is when a function remembers the variables from the scope it was created in, even after that scope is gone.
Event Loop
JavaScript can only do one thing at a time (single-threaded), but the Event Loop is the trick that makes it seem like it can multitask.
Promise
A Promise is JavaScript's way of saying 'I'll give you a value eventually — it's not ready yet, but I promise.