What is Callback Function in JavaScript: Simple Explanation and Example
callback function in JavaScript is a function passed as an argument to another function, which is then called inside that function to complete some action. It allows code to run after a task finishes, enabling asynchronous behavior and better control flow.How It Works
Imagine you ask a friend to help you with a task, and you tell them what to do once they finish. In JavaScript, a callback function works like that instruction you give your friend. You pass a function as an argument to another function, and when the main task is done, your callback function is called to continue the process.
This is useful because JavaScript often runs tasks that take time, like loading data or waiting for user input. Instead of stopping everything until the task finishes, JavaScript uses callbacks to keep things moving smoothly. When the task is ready, the callback runs to handle the result.
Example
This example shows a function that takes a callback to greet a user after a short delay.
function greetUser(name, callback) { setTimeout(() => { console.log('Hello, ' + name + '!'); callback(); }, 1000); } greetUser('Alice', () => { console.log('Greeting finished.'); });
When to Use
Use callback functions when you want to run code after another task finishes, especially for tasks that take time like reading files, fetching data from the internet, or waiting for user actions. Callbacks help keep your program responsive and organized by handling results only when they are ready.
For example, when loading a picture on a website, you can use a callback to show a message once the picture has fully loaded. This way, the page doesn't freeze while waiting.
Key Points
- A callback is a function passed into another function as an argument.
- It runs after the main function completes its task.
- Callbacks help manage asynchronous operations in JavaScript.
- They keep programs responsive by not blocking code execution.