If you understand hoisting then you should be able to predict the following outcomes:
alert(foo());
function foo() {
function bar() {
return 10;
}
return bar();
function bar() {
return 20;
}
}
if you said
20 you are correct. The previous code would be processed like this:
function foo() {
function bar() {
return 10;
}
function bar() {
return 20;
}
return bar();
}
alert(bar());
After hoisting has taken place, you can more easily see that the function
foo would return 20.
How about this one:
var x = 7;
var add = function() {
return x + y;
}
alert(add());
var y = 8;
If you answered "NaN" (not a number) then you are correct. This is because the function
add is trying to add the variable
x with the variable
y which hasn't yet been initialized. Even though it's been declared, it hasn't yet been initialized.
The previous code would be processed like this:
var x = 7;
var add;
var y;
add = function() {
return x + y;
}
alert(add());
y = 8;
You can see that by the time
add is actually called,
y has no value so it cannot be added to
x which was initialized with a value of 7.
Here's one more:
alert(words());
function words() {
function getWords() {
return "i am a function declaration";
}
var getWords = function() {
return "i am a function expression";
}
return getWords();
}
By now you can probably predict that this program will alert "i am a function expression". After hoisting this will be processed like so:
function words() {
function getWords() {
return "i am a function declaration";
}
var getWords;
getWords = function() {
return "i am a function expression";
}
return getWords();
}
alert(words());
Not much changes in the order, but you can see that the
getWords function variable name overwrites the
getWords function declaration when the code is actually executed.