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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With