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?
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:
This is behavior you should avoid, as it is specific to Firefox, even though Firefox's behavior may technically be correct.