Javascript function hoisting inside if statements
What's the deal with javascript function inside statements if
? Js just doesn't do it? The following code works fine when run in a browser. He will alert "hey" in two seconds.
<script>
setTimeout(hey,2000)
function hey(){
alert('hey')
}
</script>
But add the trival expression to this expression if
:
<script>
if(true){
setTimeout(hey,2000)
function hey(){
alert('hey')
}
}
</script>
and suddenly he complains that hey is not defined
.
Now, if you change the callback from hey
to function(){hey()}
, follow these steps:
<script>
if(true){
setTimeout(function(){hey()},2000)
function hey(){
alert('hey')
}
}
</script>
then it will start working again, even with an if statement. So what's going on?
source to share
Firefox doesn't appear to display function declarations in blocks . The behavior you see is Firefox specific and is documented in much the same way 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 a behavior that should be avoided as it is specific to Firefox, although the behavior of Firefox may be technically correct.
source to share