Take a test:
<script>
function say() { alert( "ABOVE" ); }
say();
function say() { alert( "BELOW" ); }
</script>
- The result is "BELOW" for all test (Chrome, Firefox, IE).
- How does javascript interpreter work in this case?
- http://jsfiddle.net/jcv6l/ << run the code.
function xyz() { .. }
blocks are defined at parse time. If many functions have the same name, it's the last defined which takes the precedence.However, you can define functions at runtime using statements :
will output
ABOVE
. (JSFiddle)Basically, because of hoisting, which pulls all function declarations to the top of the current scope, the interpreter is basically doing this:
That is why it always ends up alerting
below
The interpreter first reads all declarations of the functions, then executes the other statements that are outside functions. So the latter declaration overrides the former, which is why the latter was called.
In this case the interpreter parses the function definitions first and the last function definition wins.
This question has also been answered at: Ambiguous function declaration in Javascript
There is also a good article here: http://kangax.github.com/nfe/
Output:
It's because the latter function overwrites the previous one. If you try to log the function:
It will return only:
The "ABOVE" alert has been replaced with the "BELOW" alert. Similar to declaring a variable with the same name twice in the same scope - the latter would overwrite the former.
JSFiddle example.
Why? See http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html