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?