Deepak Garg
Deepak Garg

Reputation: 83

Nodejs, callback function

I am trying to understand callback function concept.

Please explain what is the difference between two snippets of code

  //callback function

function greeting(name) {
    console.log('Hello ' + name);
}

function processUserInput(callback) {
    var name = "Johny1";
    callback(name);
}

processUserInput(greeting);

and 2nd one

function greeting(name) {
    console.log('Hello ' + name);
}

function processUserInput() {
    var name = "Johny2";
    greeting(name);
}

processUserInput();

why someone uses the callback function when the same thing can be achieved by simple function?

Upvotes: 0

Views: 2391

Answers (2)

obba
obba

Reputation: 77

Callback is designed for Asynchronous code if you mean simple function is synchronous. Its means not necessary to use callback on this simple function.

Upvotes: 0

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12552

In the first example you are not hardcoding the function. So, in future processUserInput can accept another function and it will work as expected.

//callback function

function greeting(name) {
    console.log('Hello ' + name);
}
function goodbye(name) {
    console.log('Bye ' + name);
}
function processUserInput(callback) {
    var name = "Johny1";
    callback(name);
}

processUserInput(greeting); // will output Hello Johny1
processUserInput(goodbye); // will output Bye Johny1

But in the second case the greeting function is hardcoded

So, you cannot change the greeting into anything without changing the greeting function's definition.

Upvotes: 2

Related Questions