I was trying to understand the scope in JavaScript. If I declare a variable outside of a function, it is GLOBAL. Hence I tested the following code to understand sequence of execution. In the following code, I expected the "demo1" to take the global value which is "Volvo" since the I render that text before declaring the local variable with the same name inside the function. But to my surprise I see the value to be "undefined".
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var carName = "Volvo";
myFunction();
document.getElementById("demo").innerHTML = carName;
function myFunction() {
document.getElementById("demo1").innerHTML = carName;
var carName = "Volvo1";
document.getElementById("demo2").innerHTML = carName;
}
</script>
</body>
</html>
RESULT:
Volvo
undefined
Volvo1
I modified further to see what happens if a declare another Global variable inside the function as follows:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var carName = "Volvo";
myFunction();
document.getElementById("demo").innerHTML = carName;
function myFunction() {
document.getElementById("demo1").innerHTML = carName;
//declaring another global variable
carName = "Volvo1";
document.getElementById("demo2").innerHTML = carName;
}
</script>
</body>
</html>
RESULT:
Volvo1
Volvo
Volvo1
This time the "demo1" assumes the global variable declared outside of the function i.e "Volvo".
Can someone explain this to me?