sltdev
sltdev

Reputation: 459

The difference between callback and just a function being called inside of another function

Can someone please educate me on:

When should I use each scenario?

Please see my simple example below. Thank you for any help you can share.

   //func with callback passed as argument
function func1(name, fc1){
    fc1(name);
}

const printIt = (name)=>{
    console.log(name);
};

func1("samson", printIt);

//------------------------//

//func with a function called upon initial function being called. 
function func2(name1){
    //some code is called then printIt func is initialized
    printIt(name1);
}

func2('sammy');

Upvotes: 0

Views: 39

Answers (1)

Quentin
Quentin

Reputation: 943193

What's the difference between a function being passed as an argument callback function and a function being called inside of another function after some code is called?

It's the same as any time you pass an argument instead of using a hard-coded value.

You can have some logic which is consistent, and add differences in the behaviour depending on the value you pass it.

This is simple:

function add_two_numbers() { return 1 + 2; }

This is flexible:

function add_two_numbers(a, b) { return a + b; }

When should I use each scenario?

When you want either fixed or variable behaviour.

Upvotes: 2

Related Questions