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?