0

new to JS. I was trying to learn about global variable without suing var inside a function. The example code works only if I call it before the function written but calling after it, it does not work. Why it happens? here is the code.

<body>

<p id="demo"> </p>

<script>

myFunction();
// code here can use carName as a global variable
document.getElementById("demo").innerHTML = carName;
function myFunction() {
  carName = "Volvo";
}
//myFunction();        //does not work calling here, why?
</script>
</body>
Setu
  • 92
  • 1
  • 9
  • 2
    Check this https://developer.mozilla.org/en-US/docs/Glossary/Hoisting. – Andrei Yusupau Apr 11 '21 at 20:13
  • 1
    The code does not work if you call the function after the line `document.getElementById("demo").innerHTML = carName;`. You can call it just fine after the function declaration, you just need to have the line that outputs the variable after the call. – Bergi Apr 11 '21 at 22:58
  • @Bergi , thanks a lot. This is the answer what I was looking for. Instead of getting the answer other members redirected to " https://stackoverflow.com/questions/15005098/why-does-javascript-hoist-variables " where the original answer of the question is not given! and my question is closed!! – Setu Apr 12 '21 at 02:19

0 Answers0