I am reading the book 'Scope & Closures' in the series 'You Don't Know JS' and I read that functions are hoisted first and variables later. Going through this code snippet:
function foo() {
var a = 2;
function bar() {
console.log( a ); // 2
}
bar();
}
foo();
If this is the case, should the function bar() be not hoisted to the top and this code should produces error? because after hoisting, this code should be like this (at least what I understood)
function foo() {
function bar() {
console.log( a );
}
var a;
a = 2;
}
This is because function is hoisted to the top and later variables. If this is not the case, please correct me.
They're both hoisted all the way to the top, so
a
is in scope forbar
; it's not that functions are "above" variables. The only time the order comes into play is when the function declaration and variable have the same name, in which case the function declaration wins because when the variable is being hoisted, it's not created if there's already an existing binding with the given name."Hoisting" is a convenient shorthand term but it's not literal. What happens when
foo
is called (leaving out a fair bit of detail to focus on the issues in the question) is:foo
bar
anda
in your example) for that context's executionThat object is then used for handling the bindings in the execution context (e.g., the value associated with a binding is used when
a
is referenced, and set whena
is set, etc.).