Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hoisting variable declarations across script tags?

Tags:

javascript

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>
like image 826
Pardaillan Avatar asked Aug 12 '26 21:08

Pardaillan


1 Answers

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>
like image 56
Ankit Agarwal Avatar answered Aug 14 '26 10:08

Ankit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!