How to check if function exists in JavaScript?

javascript check if function exists from string
check if function exists jquery
javascript check if function is defined
check if function exists php
check if function exists sql
javascript check if function exists before defining
check if function exists python
check if value exists in object javascript

I followed this guide to create a new JS to flash communication.

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)

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
}

How to check if function exists in JavaScript?, Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true. In a few words: catch the exception. To check if a particular function name has been defined, you can use the typeof operator: if (typeof myFunctionName === 'function') { myFunctionName (); } In the given case, the typeof operator will return undefined because myFunctionName() has not been defined. So, the function call inside the IF statement won’t be executed.

I had this problem.

if (obj && typeof obj === 'function') { ... }

kept throwing a reference error if obj happened to be undefined.

In the end I did the following:

if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }

A colleague pointed out to me that checking if it's !== 'undefined' and then === 'function' is redundant of course.

Simpler:

if (typeof obj === 'function') { ... }

Much cleaner and works great.

How to check if function exist?, How to check if is function on jquery, but function is in another .js file? validation.​js: if ($.isFunction(  The solution here will break your script if variable or function not exists so your solution doesn’t make sense at all. Use .yourFunctionName instead, it’s safer especially for older browsers. In this case this is the window object, window.yourFunctionName. All global functions will be attached to the window object.

If you're using eval to convert a string to function, and you want to check if this eval'd method exists, you'll want to use typeof and your function string inside an eval:

var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"

Don't reverse this and try a typeof on eval. If you do a ReferenceError will be thrown:

var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined

Why you need to use typeof to check if a function exists with vanilla JS, Why you need to use typeof to check if a function exists with vanilla JS. if (typeof getPurchases === 'function') { getPurchases(123); } if (getPurchases) { getPurchases(123); } var myFunction = 'Some string'; // or var myFunction = 123; // This validates as true if (myFunction) { // Since myFunction isn't a Sometimes you might want to call a function in Javascript but check if the function exists before calling it. This is very simple and is covered in this post. You can test if a function exists in Javascript by simply testing for the name of it in an if() conditional.

How about:

if('functionName' in Obj){
    //code
}

e.g.

var color1 = new String("green");
"length" in color1 // returns true
"indexOf" in color1 // returns true
"blablabla" in color1 // returns false

or as for your case:

if('onChange' in me){
    //code
}

See MDN docs.

How to check whether an object exists in javascript ?, Method 1: Using the typeof operator​​ The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”. To check if a particular function name has been defined, you can use JavaScript’s typeof operator: JavaScript //Use the typeof operator to check if a JS function exists.

Didn't see this suggested: me.onChange && me.onChange(str);

Basically if me.onChange is undefined (which it will be if it hasn't been initiated) then it won't execute the latter part. If me.onChange is a function, it will execute me.onChange(str).

You can even go further and do:

me && me.onChange && me.onChange(str);

in case me is async as well.

JavaScript: Check if Function Exists Before Calling · GitHub, Sometimes you might want to call a function in Javascript but check if the function exists before calling it. This is very simple and is covered in this post. You can  The suggestion to check for the type to determine if something exists is questionable. If you’re at the point where you don’t even know a function exists or not and you haven’t designed the situation on purpose, something is very wrong and ill-planned.

How to check if a Javascript function exists, For example: A particular function exists in an external library and you do not want your code to throw a ReferenceError if that library hasn't been included properly. Let's say you use the code with the string literal, and the call to typeof returns something different later (maybe "Function" instead of "function"), because of a new/different implementation of JavaScript - it feels like it would be less likely that a new/different implementation would break the typeof Function === typeof callback check

Check if a JavaScript function is defined., In this tutorial, you will read and learn information about the two methods of checking whether a function exists in JavaScript or it has not been defined. Checking if the type is undefined will check if the variable has been defined yet. === null or !== null will only check if the value of the variable is exactly null. == null or != null will check if the value is undefined or null.

How to Check if Function Exists in JavaScript, A simple way to check if a Javascript function exists before trying to call it. This helps you avoid common function undefined error. How to check if function exists in javascript Javascript might not be happy if you call function before it is being created. This can happen in a couple of cases.

Comments
  • @SteveChambers I have done that. Thank you for reminding me.
  • Possible duplicate of How to tell if a Javascript function is defined
  • catch the Exception. check my answer
  • === 'function' would be better than != 'undefined'
  • @James, because that statement actually throws an undefined exception in the JavaScript. I tried it.
  • @UpTheCreek, it would be a bit dangerous as a general solution since older versions of IE treat certain functions as objects, e.g. typeof window.alert === 'object'.
  • Why not just use if (me.onChange) { // do something } ?
  • @BornToCode because then me.onChange could be anything evaluating to true, not necessarily a function (e.g. it could be a boolean, a string, etc). For example see jsfiddle.net/j5KAF/1
  • Anyone has idea why the first code snippet throws ReferenceError? That seems illogical to me.
  • @saidfagan See the definition of ReferenceError developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • eval == evil ;)
  • It might be evil, but this is very helpful when the function name is in a variable.
  • You can do this without eval. Example: var a = 'alert'; window[a]('it works');