HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to check if function exists in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfunctioncheckexistsjavascript

Problem

My code is

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}


However, sometimes my onChange does not load. Firebug errors with


me.onChange is not a function

I want to degrade gracefully because this is not the most important feature in my program. typeof gives the same error.

Any suggestions on how to make sure that it exists and then only execute onChange?

(None of the methods below except try catch one work)

Solution

Try something like this:

if (typeof me.onChange !== "undefined") { 
    // safe to use the function
}


or better yet (as per UpTheCreek upvoted comment)

if (typeof me.onChange === "function") { 
    // safe to use the function
}

Code Snippets

if (typeof me.onChange !== "undefined") { 
    // safe to use the function
}
if (typeof me.onChange === "function") { 
    // safe to use the function
}

Context

Stack Overflow Q#1042138, score: 1632

Revisions (0)

No revisions yet.