Why does shadowed variable evaluate to undefined when defined in outside scope?

javascript, shadowing, variables

Solution

In the first case, your code is accessing the global variable "outside_scope", which has been initialized to "outside scope".

Javascript has function level scope, so in the second case it is accessing the function scoped variable "outside_scope", but it has not yet been initialized at the time of the alert box. So it displays undefined.

Problem

Consider the following piece of code: ``` <html><head></head> <body> <script type="text/javascript"> var outside_scope = "outside scope"; function f1() { alert(outside_scope) ; } f1(); </script> </body> </html> ``` The output for this code is that the alert box displays the message "outside scope". But, if I slightly modify the code as: ``` <html><head></head> <body> <script type="text/javascript"> var outside_scope = "outside scope"; function f1() { alert(outside_scope) ; var outside_scope = "inside scope"; } f1(); </script> </body> </html> ``` the alert box displays the message "undefined". I could have understood the logic if it displays "undefined" in both the cases. But, that is not happening. It displays "undefined" only in the second case. Why is this? Thanks in advance for your help!

Original source