The beginning is here “2.2.5. Hoisting: A Problem with Scattered vars”:
“JavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function. This behavior is known as hoisting.”
It means very simple thing: you can start using variable even if it has been declared later in the function. As it is being hoisted at interpretation/parse time (simplification), and it is ok! it just has ‘undefined’ value.
myname = "global";
function func() {
console.log(myname);
var myname = "local";
console.log(myname);
}
func();
you get:
>>undefined
>>local
Just to compare with Python: in similar example there you get “NameError: global name 'myname' is not defined”
Actually even this was surprise for me but wait... things start getting funnier when function declaration and function expression are getting involved.
You know the difference between function declaration and function expression, right? ;)
Just if you don’t (btw I didn’t) It is described here “4.1.2. Declarations Versus Expressions: Names and Hoisting”
So let’s start the party! Here is slightly modified example from here “4.1.4. Function Hoisting”:
function foo() { console.log( 'global foo' ); }
function bar() { console.log( 'global foo' ); }
function hoistMe() {
foo();
bar();
}
hoistMe();
You get:
>> global foo
>> global foo
Absolutely expected! Now next example:
function hoistMeMore() {
foo();
bar();
function foo() {
console.log( 'local foo' )
}
var bar = function () {
console.log( 'local bar' );
};
}
hoistMeMore();
You get:
>>local foo
>>TypeError: bar is not a function
‘local foo’ is expected, right? But why ‘Type Error’? Because! In function expression (which is different from function declaration) variable bar is being hoisted but function definition is not! That’s it!
Enjoy the book! :)
Add a comment