How can a variable
declared in if
condition is hoisted and not function
?
Example 1:
var x = 1;
if(a = 1) {
x += typeof a;
}
x; // 1number
a; // 1
When tried same with function
in SpiderMonkey
and V8
hoisting didn't happen. Why not? What happens to function in if
condition?
Example 2:
var x = 1;
if ( function f () { return 9; } ) {
x += typeof f;
}
x; // 1undefined
f; // ReferenceError: f is not defined
However when function is defined inside if
on success function is hoisted
Example 3:
var x = 1;
if ( true ) {
x += typeof f;
function f() { return 1; }
}
x; // 1function
f; // f()
typeof f; // function
Even if condition is false function is hoisted Example 4:
var x = 1;
if ( false ) {
x += typeof f;
function f() { return 1; }
}
x; // 1
f; // undefined not ReferenceError: f is not defined
// f still got hoisted
What's happing at example 2? Why function is not hoisted when variable did in example 1?