Callbacks
Expert-Level Explanation
Callbacks in JavaScript are functions passed into other functions as arguments and are executed after some operation is complete. They are used for asynchronous operations like handling events or fetching data.
Creative Explanation
A callback is like ordering food at a restaurant. You place your order (call a function) and give your table number (pass a callback). When your order is ready, the waiter brings it to your table (the callback is called).
Practical Explanation with Code
function fetchData(callback) {
// Simulate fetching data
setTimeout(() => {
callback('Data received');
}, 1000);
}
fetchData((data) => {
console.log(data); // Output: Data received
});
Real-world Example
Callbacks are like asking a friend to notify you when the pizza delivery arrives. You continue with other activities, and your friend lets you know (calls back) when the pizza is here.