Click here to Skip to main content
15,916,215 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
what is the difference between example 1 and example 2:

Example 1:
C#
function a () {
    console.log("A is running");
    b();
    
}

 function b () {
    console.log("B is running")
}

a();

Example 2:
C#
const fun1 = function a (callback) {
    console.log("A is running");
    callback();   
}

const fun2 = function b() {
    console.log("B is running");
}

fun1( fun2 );

output: A is running
B is running

why we pass function as a parameter when we can do this? Or this is because of difference between function definition and function expression?
can anyone explain me please?
and in example 2 which one is callback function
fun1 or fun2

What I have tried:

I am learning callback function. so i just got example 1 on my mind.
Posted
Updated 24-Aug-20 3:36am
v3

The difference is that in the first example "a" can only then go on to call "b" as the call to "b" is hard-coded in "a". In the second example the calling code decides what function "a" calls, so it could be "b", it could be "c", it could even be null if it doesn't want "a" to do a follow-up call.
 
Share this answer
 
The callback function is important to us, Its works as an argument passing in the function.

Its something required asynchronous function called and think, you need to wait for that response and want to process that response ahead that could be achievable by callback.

Example :

JavaScript
function a(cb){
   var a = 10;
   var b= 10; 
   setTimeout(function(){cb(c)},2000);
   c = a+b;
}

a(result=>{
  if(result){
   console.log(result)
}
})
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900