Reputation: 459
Can someone please educate me on:
callback function
and a function being called inside of another
function after some code is called?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
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