Function Declarations vs. Function Expressions
Question 1:
function foo(){ |
Question 1 uses function declarations which means they get hoisted.
“Function declarations and function variables are always moved (‘hoisted’) to the top of their JavaScript scope by the JavaScript interpreter.”
When a function declaration is hoisted the entire function body is lifted with it, so after the interpreter has finished with the code in Question 1 it runs more like this:
//**Simulated processing sequence for Question 1** |
Question 2
function foo(){ |
Do Function Expressions get Hoisted too?
That depends on the expression.
var bar = function() { |
The left hand side (var bar) is a Variable Declaration. Variable Declarations get hoisted but their Assignment Expressions don’t. So when bar is hoisted the interpreter initially sets var bar = undefined. The function definition itself is not hoisted.
Thus the code in Question 2 runs in a more intuitive sequence://**Simulated processing sequence for Question 2**
function foo(){
//a declaration for each function expression
var bar = undefined;
var bar = undefined;
//first Function Expression is executed
bar = function() {
return 3;
};
// Function created by first Function Expression is invoked
return bar();
// second Function Expression unreachable
}
console.log(foo()); //3
Question 3
console.log(foo()); |
function foo(){ |
Question 4
function foo(){ |
//**Simulated processing sequence for Question 4** |