Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 463
BeachRunnerFred Avatar asked Oct 06 '09 21:10

BeachRunnerFred


2 Answers

This is due to something called the hoisting of variable declarations.

Basically, JavaScript separates a variable declaration in two, leaving the assignment where you did the declaration and hoisting the actual declaration to the top of the function:

var f1 = function ()  {
   // some code
   var counter = 0;
   // some more code
}

var f2 = function () {
   var counter; // initialized with undefined
   // some code
   counter = 0;
   // some more code
}

On run-time, f1() gets translated into f2(). I wrote an in depth blog post about this here. I hope this helps you understand what happens in your code.

This is also the reason, it is recommended to declare your variables at the top of a function in JavaScript. It helps you understand what the code does, when it runs.

like image 55
Pierre Spring Avatar answered Oct 21 '22 05:10

Pierre Spring


Variables are subject to hoisting. This means that regardless of where a variable is placed within a function, it is moved to the top of the scope in which it is defined.

For example:

var outside_scope = "outside scope";
function f1() {
    alert(outside_scope) ;
    var outside_scope = "inside scope";
}
f1();

Gets interpreted into:

var outside_scope = "outside scope";
function f1() {
    var outside_scope; // is undefined
    alert(outside_scope) ;
    outside_scope = "inside scope";
}
f1();

Because of that, and the function only scope that JavaScript has, is recommended to declare all the variables at the top of the function, to resemble what will happen.

like image 25
Christian C. Salvadó Avatar answered Oct 21 '22 07:10

Christian C. Salvadó