Possible Duplicate:
Why does second function declaration win even though I return before it?
I’d like to understand one thing. Does JS first go through the code to initialize variables, functions, etc. before implementing any function or output? I mean it looks like it goes through the code twice – one time to initialize and only for the second time it begins to do something. Right?
I have such code:
alert( (function f() {
function f() { return 1 }
return f();
function f() { return 2 }
})() );
The output is 2. So if it begins to implement the code right from the first time, the output would be 1. But as far as output is 2 it first checks the code and only then begins to work with it. Am I right?
Javascript does “hoisting”. This basically means that any
var nameorfunction name()is hoisted to the top of whatever function body it’s declared in. So your example could be re written like this, which obeys hoisting rules.What’s happening here is that in the outer scope, you make a local variable
f. You then assign a function to it, and then execute that function.Inside the function, we create a new local variable
f, which shadows the outer one, making it inaccessible. We now have a totally differentfthat only exists in this inner function. We assign the first function to it, and then the second hoisted function right after. Now we execute our function body.As a result, you almost never want to use the
function name() {}syntax for creating functions because of hoisting. Instead, usevar name = function() {}to create functions.It’s far more controllable and understandable because declaring the variable and assigning a value to it are now 2 separate operations. The variable declaration is still hoisted, but it won’t have a value until it reaches the line of code that assigns a function to it, which is usually what you actually want.