How can I conditionally define a function in javascript?

To assure your function has not been defined before, use :

if ( typeof yourFunctionName == 'undefined' ) {
  yourFunctionName = function( params ) {
    // your code here
  };
}

You can make them function expressions instead of function declarations:

if (false)​ {
    var foo = function () {
        alert("FOO");
    };
}
foo(); //TypeError: undefined is not a function

Note that in the above code, foo is still accessible even though the condition evaluated to false. This is because function-scoped declarations (both function and var) are hoisted to the top of the scope in which they are declared. However, assignments happen at the point in the code where they appear.

What the above code is effectively doing is this:

var foo; //No assignment, foo is undefined
if (false)​ {
    foo = function () {
        alert("FOO");
    };
}
foo(); //TypeError: undefined is not a function

Warning - Named function expressions are still hoisted in Internet Explorer 8 and below (this is a bug in IE). Obviously this is only a potential problem if you need to support old browsers.

Tags:

Javascript