0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.