Pardaillan
Pardaillan

Reputation: 51

Hoisting variable declarations across script tags?

I have the following code inserted into a html file:

<script>
	console.log(myVar);
	var myVar = 1;
</script>

After opening this html page in a browser the value of myVar will be undefined. As far as I understood this is a normal behavior in javascript as first it sets the memory space and then it executes the code.

Now the weird part is if we split this like this for the same html page:

<script>
	console.log(myVar);
</script>

<script>
	var myVar = 1;
</script>

the result will be: Uncaught ReferenceError: myVar is not defined

Why?

This is not about variable's scope, it is about hoisting and it seems that hoisting is only inside a javascript block and not available for the whole loaded page in other javascript blocks. The same example here:

<script>
	myFunc();

  function myFunc() {
		console.log('Hello!');
	}
</script>

VS

<script>
	myFunc();
</script>


<script>
	function myFunc() {
		console.log('Hello!');
	}
</script>

Upvotes: 3

Views: 821

Answers (3)

Bergi
Bergi

Reputation: 664599

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.

Upvotes: 1

Nathan Barteaux
Nathan Barteaux

Reputation: 11

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)

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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>

Upvotes: 3

Related Questions