What is a callback function in JavaScript?
Asked by Alice Chen27 days ago
20 views
Can someone explain callbacks with an example?
0
1 answers
1 Answer
A **callback function** in JavaScript is a function that is passed as an argument to another function and is intended to be executed after some kind of event or operation has completed. Callbacks are a fundamental way to handle asynchronous tasks, such as reading files, making network requests, or waiting for user interactions.
Here’s a simple example to illustrate how callbacks work:
```javascript
function greet(name, callback) {
console.log('Hello, ' + name + '!');
callback();
}
function sayGoodbye() {
console.log('Goodbye!');
}
greet('Alice', sayGoodbye);
```
In this example, the `greet` function takes two parameters: a `name` and a `callback` function. It first prints a greeting message, then calls the `callback` function. When we call `greet('Alice', sayGoodbye)`, it outputs:
```
Hello, Alice!
Goodbye!
```
This shows how the `sayGoodbye` function is passed as a callback and executed after the greeting. Callbacks are especially useful in asynchronous programming to ensure certain code runs only after an operation finishes, preventing blocking of the main thread.
If you want to learn more, modern JavaScript also offers Promises and async/await syntax for handling asynchronous code, which can sometimes make working with callbacks easier and more readable.
0
0
by Daniel Garcia15 days ago
