Weird behavior in referring to global variable. Is this a bug in javascript? Surely it isn't!

Posted by Chandan . on Stack Overflow See other posts from Stack Overflow or by Chandan .
Published on 2009-02-25T12:06:15Z Indexed on 2010/05/27 0:21 UTC
Read the original article Hit count: 195

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about variables