In this lesson, you will understand how to use callback functions in JavaScript and learn about execution order.
A callback function is a function that is passed into another function as an argument. It is called at a later time when a certain event occurs. For example, think about how you call a friend and say, “Call me back when you arrive.” Here, you’re asking your friend to call you, which is like telling a callback to execute.
File: callback-example.js
function greetUser(name, callback) {
console.log('Hello, ' + name + '!');
callback();
}
function endGreeting() {
console.log('Have a great day!');
}
greetUser('Alice', endGreeting);
Hello, Alice!
Have a great day!
In this example, we define two functions: greetUser and endGreeting. The greetUser function takes a name and a callback function. When you call greetUser, it greets the user and calls the callback function once it’s finished. This allows us to control when the second function runs.
Your task is to create a function that simulates preparing a meal. Use a callback function to notify when the meal is ready. Write a function named prepareMeal, and a callback function named serveMeal.
function prepareMeal(meal, callback) {
console.log('Preparing ' + meal + '...');
callback();
}
function serveMeal() {
console.log('Meal is ready to be served!');
}
prepareMeal('pasta', serveMeal);
callback(); at the right spot.