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>