How exactly is JavaScript interpreted?

I always thought that browsers execute JavaScript code from top to bottom in lines (you expect this behavior in a scripting language). But this is clearly not the case:

//works great

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

but if I declare the function as a variable, it fails with "Unused ReferenceError: test not defined":

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

Therefore, the javascript mechanism sometimes does not execute code from top to bottom. It can somehow preload functions, even if they are declared at the end. How exactly does it work and why?

+7
source share
1 answer

This is an example of raising functions and variables: declarations of functions and variables move to the top of the current area.

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 conclude that in the second case, the test variable is undefined when you try to execute it.

+9
source

All Articles