0

I understand why the following variable with a global scope is reachable for displaying:

<script>

    var carName = "Volvo";

    myFunction();

    function myFunction()
    {
        document.getElementById("demo").innerHTML = "I can display " + carName;
        // I can display Volvo
    }

</script>

However, I cannot understand why the var keyword would make the following 2 snippets different.

I can see the difference, but I cannot see why one would be undefined whereas the other would be reachable. Could someone please help me understand the distinction?

<script>

    myFunction();

    document.getElementById("demo").innerHTML = "The type of carName is " + typeof carName;
    // The type of carName is undefined.

    function myFunction()
    {
        var carName = "Volvo";
    }

</script>


<script>

    myFunction();

    document.getElementById("demo").innerHTML = "I can display " + carName;
    // I can display Volvo

    function myFunction()
    {
        carName = "Volvo";
    }

</script>
  • 1
    Because in the function `myFunction` you are limiting the scope by using `var`. See more on scope [here](http://stackoverflow.com/a/500459/4790490) – Hardik Pithva Jun 10 '16 at 13:02
  • Got it. Thank you Hearty and meskobalazs. –  Jun 10 '16 at 13:12

1 Answers1

2

var has a function scope. If you don't use it, it will be implicitely put into global scope in non-strict mode.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63