Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if function exists in JavaScript?

Tags:

javascript

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)

like image 265
Alec Smart Avatar asked Jun 25 '09 04:06

Alec Smart


People also ask

How do you check if a function exists in JS?

Use an if Conditional Statement The code in the brackets will execute if the function is defined. If instead you just test the function without using the window object, for example as if(aFunctionName) , JavaScript will throw a ReferenceErorr if the function doesn't exist.

How do you know if a function exists using typeof operator?

The typeof operator gets the data type of the unevaluated operand which can be a literal or a data structure like an object, a function, or a variable. The typeof returns a string with the name of the variable type as a first parameter (object, boolean, undefined, etc.).

Is a function in JS?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.


2 Answers

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 } 
like image 180
Andrew Hare Avatar answered Sep 18 '22 06:09

Andrew Hare


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.

like image 39
Misha Nasledov Avatar answered Sep 18 '22 06:09

Misha Nasledov