I tried to understand the scope of JavaScript. If I declare a variable outside the function, it is GLOBAL. So I checked the following code to understand the sequence of execution. In the following code, I expected "demo1" to get a global value, which is "Volvo", as I render this text before declaring a local variable with the same name inside the function. But, to my surprise, I see the value "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 find out what happens if you 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; </script> </body> </html>
RESULT:
Volvo1
Volvo
Volvo1
This time, "demo1" accepts a global variable declared outside the ie function of "Volvo".
Can someone explain this to me?
javascript scope html hoisting variable-declaration
Sigma
source share