Aim of the puzzle: Use a function that takes a callback function as an argument.
Walk through of solution: In this puzzle, there are 3 functions declared: orderGroceries()
, orderPizza()
, and scheduleDinner()
.
orderGroceries()
and orderPizza()
are simple functions that print a message to the console using console.log()
.
The last one, scheduleDinner()
, is special. It takes both a string (day
) and a function (mealFunction
) as an argument. When a function is used as an argument, it is called a callback function. Using a callback function makes scheduleDinner()
more flexible, as it can run either orderGroceries
or orderPizza
, depending on which one it takes as a callback.
Below the function declarations, scheduleDinner('Monday', orderPizza)
calls the scheduleDinner()
function with 'Monday'
as day
and orderPizza
as the callback mealFunction
.
To complete the puzzle, call scheduleDinner()
again. Give it a day of the week (as a string) for the first argument, and then either orderPizza
or orderGroceries
as a callback.
Sample code solution:
function orderGroceries(day) {
console.log('Groceries will be ordered on ' + day);
}
function orderPizza(day) {
console.log('Pizza will be ordered on ' + day);
}
function scheduleDinner(day, mealFunction) {
console.log('Scheduling dinner...');
mealFunction(day);
}
scheduleDinner('Monday', orderPizza);
scheduleDinner('Tuesday', orderGroceries);
Javascript Concepts: Functions, Callback Functions, Strings, console.log()