Consider the following piece of code.
<html> <body> <script> var x = 5; //globally declared function showX() { alert('x='+x); //trying to display global value var x=10; //trying to create and initialize a local x } </script> <input type = 'button' value='Show X' onclick='showX()'> </body> </html>
The alert statement shows ‘x=undefined’. And doesn’t print the global value of x as expected. An equivalent java code would display 5! So, is it a bug? If not then how does one explain that behavior?
The ECMAScript Specification says in section 12.2:
So it’s not a bug – the local variable is created when the function is entered.