ECMA-262 may appear to not allow conditional function declarations, however there is a loophole that permits them. In most browsers the following will print "bar!!" but in Firefox it will throw a reference error since bar has not been defined.
function foo() {
if (!bar) {
console.log('no bar');
function bar(){}
} else {
console.log('bar!!');
}
}
foo()
To avoid the reference error, you can use:
if (typeof bar == 'undefined')
however it's not a good idea to use conditional declarations due to the different behaviour in different browsers. A function expression can be used instead:
if (typeof bar == 'undefined') {
bar = function(){};
}
that will conditionally create a global bar function in all browsers. A variable declaration will create the function only in the current execution context
if (typeof bar == 'undefined') {
var bar = function(){};
}