Peterson Peterson - 4 years ago 122
Javascript Question

Callback Example Not Working Properly

I have following simple example to demonstrate callback function:

// 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);

Expected Result

The number you provided is 6
The meaning of life is: 42

Real Result

The number you provided is 6

Why I am not getting the second line while running this example for callback function?

Answer Source

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.


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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download