When you start learning JavaScript, you often come across the term “callback function.” It’s a fundamental concept in JavaScript programming, but it can be a bit confusing at first. Let’s break it down in simple terms.
What is a Callback Function?
In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. Think of it as a recipe: you have the main function (the chef) that performs some task, and the callback function (the helper) that is called once the task is done.
Example of a Callback Function
Let’s consider a scenario where you want to load some data from a server and then display it on a webpage. You would use a callback function to handle the data once it’s been loaded. Here’s a simple example:
`function loadData(callback) {
// Simulate loading data from a server
setTimeout(() => {
const data = { message: "Hello, world!" };
callback(data);
}, 2000);
}
function displayData(data) {
console.log(data.message);
}
loadData(displayData);`
Top comments (0)