Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function hoisting inside of if statements

What's the deal with javascript function hoisting inside of if statements? Does js just not do it? The following code, when run in a browser works just fine. It will alert "hey" after two seconds.

<script>
setTimeout(hey,2000)
function hey(){
    alert('hey')
}
</script>

But add a trival if statement around this:

<script>
if(true){
setTimeout(hey,2000)

function hey(){
    alert('hey')
}
}
</script>

and suddenly it complains that hey is not defined.
Now if you change the callback from hey to function(){hey()}, like this:

<script>
if(true){
setTimeout(function(){hey()},2000)

function hey(){
    alert('hey')
}
}
</script>

then it starts working again, even with the if statement. So what's going on?

like image 329
J-bob Avatar asked May 28 '26 22:05

J-bob


1 Answers

Firefox doesn’t hoist function declarations in blocks, apparently. The behavior you're seeing is specific to Firefox, and documented nearly identically elsewhere.

To paraphrase:

Works:

if ( hasRequiredJQueryVersion ) {
   // Test data here
   // Library code here
}

Works everywhere except Firefox:

if ( true ) {
    testFunction();
    function testFunction() {
        alert(‘testFunction called’);
    }
}

This is behavior you should avoid, as it is specific to Firefox, even though Firefox's behavior may technically be correct.

like image 151
meagar Avatar answered May 30 '26 10:05

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!