I have following simple example to demonstrate callback function:
<script>
// The callback method
function meaningOfLife() {
console.log("The meaning of life is: 42");
}
// A method which accepts a callback method as an argument
function printANumber(number, meaningOfLife) {
console.log("The number you provided is: " + number);
}
// Driver method
printANumber(6, meaningOfLife);
</script>
The number you provided is 6
The meaning of life is: 42
The number you provided is 6
Why I am not getting the second line while running this example for callback function?
The printANumber
method accepts a callback as an argument, but never calls it (or does anything else with it).
Just passing a value to a function does nothing except populate the argument with that value.
If you want to use that value, then use it.
meaningOfLife();
This would be clearer if you didn't reuse variable names. You have two different variables both called meaningOfLife
. Let's change that:
function printANumber(number, callback) {
console.log("The number you provided is: " + number);
callback();
}