Please note: ^ This question is not a duplicate to a let/const question as that is unrelated. The same question remains regardless if it was var
, let
, or const
since that is unrelated to the intent of the question.
I would really appreciate some clarification on function hoisting within another function. This is what I understand clearly so far:
This does not work because anotherFunc
is being called in the file before it's created and const
does not hoist before it's created.
const someFunc = () => {
console.log('someFunc called');
}
anotherFunc(); // anotherFunc is not defined error
const anotherFunc = () => {
console.log('anotherFunc called');
}
This works because anotherFunc
is a function declaration and they are hoisted to the top as per JS rules:
anotherFunc(); // anotherFunc called
function anotherFunc() {
console.log('anotherFunc called');
}
Doesn’t work because it’s a function expression and since they are assigned to a var
variable, the variable will be hoisted to the top and undefined initially:
anotherFunc(); // anotherFunc is not a function at <anonymous>
var anotherFunc = function () {
console.log('anotherFunc called');
}
So can someone explain to me why this works(see below)? This is a step deeper from everything explained online.
If a function is declared later but is called inside another function before it, why does it work? This has something to do with JS execution order?
const someFunc = () => {
console.log('someFunc called');
anotherFunc();
}
const anotherFunc = () => {
console.log('anotherFunc called');
}
someFunc(); // 'someFunc called' 'anotherFunc called'
Is it because someFunc
and anotherFunc
are first assigned by JS in memory so then calling them later doesn't matter what order they are in?
Lastly, does this differ for const/let/var functions in the same scenario(the last one)?
Thank you so much for the clarification!