Testing if JavaScript method Exists

When developing within a large web application it may be needed to check if a JavaScript function/object exists prior to being calling. The benefits to checking if the method exists are:

  1. No JavaScript errors are Generated.
  2. if needed you can dynamically load and initialize your method or object

In most cases you won’t need to test for a function but in the rare cases that you find yourself not sure of what has been loaded into the DOM (Document Object Model) you can check by simply calling window.methodName. By wrapping it in a if statement it will let you know if the method exists.

if( window.methodname ) {
  // method exists
} else {
  // method does not exist
  function methodName() {

  }
}

Comments & Questions

Add Your Comment