setTimeout uses callback [ many other functions can also use callbacks]
It just means that a function that is passed as an argument to another function which then invokes the passed function inside itself.....
When you repeatedly call the outside function which calls another outside function it is called callback-hell or pyramid-of-doom
function greet(name,callback){
console.log("Hello ",name);
callback();
}
function sayBye(){
console.log("Bye!");
}
greet("Dark Alpha",sayBye); // sayBye is the call back function that I am passing as an argument to greet
does it happen becuase of hoisting?
wait js doesn't hoist functions?
True and not true !
JS hoists function declaraction like
sayHi();
function sayHi(){
console.log("Hi!");
}
not function expressions like :
sayHi();
let sayHi()= ()=<{
console.log("Hi!");
}
This happens primarily and descretely becuase -
- You can pass functions as an argument
- You can store them in variables
- You can return them from another function
All these makes function first-class ciitzens in js.
Hoisting helps when you define a callback as a function declaration above the point where it is being used, but it's not the reason callbacks works.
takeaway:
- callbacks works due to first-class function behavior
- Hoisting helps with first class function behavior, not expressions
- callbacks happen regardless of hoisting