I have the following code inserted into a html file:
Why? Because the second script is not considered when the first one runs. The behaviour you describe, declaring all variables first before executing code, applies only to every individual block of code.
In the above code the <script>
with console.log(myVar)
is rendered first and the system looks for the myVar
variable in the global and local scope. Since, the variable is not found till this point it raises, Uncaught ReferenceError: myVar is not defined
error as var myVar = 1;
is rendered in the next <script>
block.
<script>
console.log(myVar);
</script>
<script>
var myVar = 1;
</script>
But when you change the order of the <script>
blocks to something like below then it will work
<script>
var myVar = 1;
</script>
<script>
console.log(myVar);
</script>
MyVar is now defined in the scope of your second example (even though it might be in example 1). In your final block of code, myVar is declared. I highy reccomend reading about variable scope in JavaScript (and Java)