Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly is JavaScript interpreted? [duplicate]

Tags:

javascript

I've always thought that browsers execute JavaScript code from top to bottom string by string(you kinda expect this behavior from a scripting language). But clearly it's not the case here:

//works perfect

<script>
  test();
  function test() { alert('test'); }
</script>

but if I declare function as a variable it fails with 'Uncaught ReferenceError: test is not defined':

<script>
  test();
  var test = function() { alert('test'); }
</script>

So the javascript engine sometimes doesn't execute the code from top to bottom. It can somehow preload functions even if they're declared in the end. How exactly does it work and why?

like image 979
Kirill Ivlev Avatar asked May 24 '13 22:05

Kirill Ivlev


1 Answers

This is an example of function and variable hoisting: function and variable declarations get moved to the top of the current scope.

Your examples are internally converted to this:

Case 1:

<script>
  function test() { alert('test'); }
  test();
</script>

Case 2:

<script>
  var test;
  test();
  test = function() { alert('test'); }
</script>

From this you can infer, that in the second case the variable test is undefined, when you try to execute it.

like image 87
Sirko Avatar answered Sep 29 '22 14:09

Sirko