Why is function variable undefined when var comes after it?

I've read that a good practice is to put a var statement which defines all local variables at the top of each function. The following code shows why this is a good idea, since apparently a var after a variable is used makes it undefined.

But can someone tell me why this is the case?

<html>
    <head>
        <script type="text/javascript">
            window.onload = function() {
                var a=1;
                function foo() {
                    //a = 2; //outputs 2,2 because this overwrites the external variable value
                    //var a = 2; //outputs 2,1 because the "var" keyword creates a second variable with local scope which doesn't affect the external variable 
                    console.log(a);
                    var a = 3; //ouputs "undefined,1" ???
                }
                foo();
                console.log(a);
            };
        </script>
    </head>
    <body>

    </body>
</html>

Answers:

Answer
function foo() {
  console.log(a);
  var a = 3;
}

is equivalent to

function foo() {
  var a;
  console.log(a);
  a = 3;
}

because in JavaScript variable declarations are hoisted but initializers are not.

You can see that this is literally true with the following example:

e = 0;
function foo() {
  e = 1;
  try {
    throw 2;
  } catch (e) {
    var e = 3;
    alert("In catch " + e);
  }
  alert("Before end of function " + e);
}
foo();
alert("Outside function " + e);

which alerts

In catch 3
Before end of function 1
Outside function 0

because the variable declaration is hoisted so the e outside the function is not changed by e = 1, but the e = 3 occurs inside the catch so the 3 does not affect the e at the end of the function, instead over-writing the exception value.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.