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?
Kir Ivlev
source share