How to check if function exists in JavaScript?

Javascript

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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
}

Solution 2 - Javascript

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.

Solution 3 - Javascript

Modern JavaScript to the rescue!

In 2022, this is solved* in JavaScript (and TypeScript) with the new Optional Chaining syntax.

me.onChange?.(str)

If onChange exists, it gets called.

If onChange does not exist, nothing happens: the expression returns undefined.

So for let value = me.onChange?.(str), value will be undefined if onChange does not exist.

Note, if onChange exists but is not a function, it throws a TypeError just the same as if you call any non-function as a function. Optional Chaining doesn't do any magic to make this go away.

* Optional Chaining is a stage 4 TC39 proposal, meaning it's not officially in the ECMAScript spec yet, but is essentially guaranteed to be included in the next version. You can use it today via Babel or TypeScript with confidence the syntax won't change.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

Try typeof -- Look for 'undefined' to say it doesn't exist, 'function' for a function. JSFiddle for this code

function thisishere() {
    return false;
}
alert("thisishere() is a " + typeof thisishere);
alert("thisisnthere() is " + typeof thisisnthere);

Or as an if:

if (typeof thisishere === 'function') {
    // function exists
}

Or with a return value, on a single line:

var exists = (typeof thisishere === 'function') ? "Value if true" : "Value if false";
var exists = (typeof thisishere === 'function') // Returns true or false

Solution 8 - Javascript

For me the easiest way :

function func_exists(fname)
{
  return (typeof window[fname] === 'function');
}

Solution 9 - Javascript

//Simple function that will tell if the function is defined or not
function is_function(func) {
    return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}

//usage

if (is_function("myFunction") {
        alert("myFunction defined");
    } else {
        alert("myFunction not defined");
    }

Solution 10 - Javascript

Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true.

function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false

Solution 11 - Javascript

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

Solution 12 - Javascript

I'll go 1 step further to make sure the property is indeed a function

function js_to_as( str ){
     if (me && me.onChange && typeof me.onChange === 'function') {
         me.onChange(str);
     }
}

Solution 13 - Javascript

function function_exists(function_name)
{
	return eval('typeof ' + function_name) === 'function';
}
alert(function_exists('test'));
alert(function_exists('function_exists'));

OR

function function_exists(func_name) {
  //  discuss at: http://phpjs.org/functions/function_exists/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Steve Clay
  // improved by: Legaev Andrey
  // improved by: Brett Zamir (http://brett-zamir.me)
  //   example 1: function_exists('isFinite');
  //   returns 1: true

  if (typeof func_name === 'string') {
	func_name = this.window[func_name];
  }
  return typeof func_name === 'function';
}

Solution 14 - Javascript

I like using this method:

function isFunction(functionToCheck) {
  var getType = {};
  return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}

Usage:

if ( isFunction(me.onChange) ) {
    me.onChange(str); // call the function with params
}

Solution 15 - Javascript

The Underscore.js library defines it in the isFunction method as this (which comments suggest may cater for some browser bugs)

typeof obj == 'function' || false

http://underscorejs.org/docs/underscore.html#section-143

Solution 16 - Javascript

I had the case where the name of the function varied according to a variable (var 'x' in this case) added to the functions name. This works:

if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); } 

Solution 17 - Javascript

If you're checking for a function that is a jQuery plugin, you need to use $.fn.myfunction

if (typeof $.fn.mask === 'function') {
    $('.zip').mask('00000');
}

Solution 18 - Javascript

Here is a working and simple solution for checking existence of a function and triggering that function dynamically by another function;

Trigger function

function runDynamicFunction(functionname){ 
	
	if (typeof window[functionname] == "function") { //check availability

		window[functionname]("this is from the function it"); // run function and pass a parameter to it
	}
}

and you can now generate the function dynamically maybe using php like this

function runThis_func(my_Parameter){

	alert(my_Parameter +" triggerd");
}

now you can call the function using dynamically generated event

<?php

$name_frm_somware ="runThis_func";

echo "<input type='button' value='Button' onclick='runDynamicFunction(\"".$name_frm_somware."\");'>";

?>

the exact HTML code you need is

<input type="button" value="Button" onclick="runDynamicFunction('runThis_func');">

Solution 19 - Javascript

In a few words: catch the exception.

I am really surprised nobody answered or commented about Exception Catch on this post yet.

Detail: Here goes an example where I try to match a function which is prefixed by mask_ and suffixed by the form field "name". When JavaScript does not find the function, it should throw an ReferenceError which you can handle as you wish on the catch section.

function inputMask(input) {
  try {
    let maskedInput = eval("mask_"+input.name);

    if(typeof maskedInput === "undefined")
        return input.value;
    else
        return eval("mask_"+input.name)(input);

  } catch(e) {
    if (e instanceof ReferenceError) {
      return input.value;
    }
  }
}

Solution 20 - Javascript

With no conditions

me.onChange=function(){};

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

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

Solution 21 - Javascript

I would suspect that me is not getting correctly assigned onload.

Moving the get_ID call into the onclick event should take care of it.

Obviously you can further trap as previously mentioned:

function js_to_as( str) {
  var me = get_ID('jsExample');
  if (me && me.onChange) {
    me.onChange(str);
  }
}

Solution 22 - Javascript

I always check like this:

if(!myFunction){return false;}

just place it before any code that uses this function

Solution 23 - Javascript

This simple jQuery code should do the trick:

if (jQuery.isFunction(functionName)) {
    functionName();
}

Solution 24 - Javascript

I have tried the accepted answer; however:

console.log(typeof me.onChange);

returns 'undefined'. I've noticed that the specification states an event called 'onchange' instead of 'onChange' (notice the camelCase).

Changing the original accepted answer to the following worked for me:

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

Solution 25 - Javascript

I have also been looking for an elegant solution to this problem. After much reflection, I found this approach best.

const func = me.onChange || (str => {}); func(str);

Solution 26 - Javascript

I would suggest using:

function hasMethod(subject, methodName) {
  return subject != null && typeof subject[methodName] == "function";
}

The first check subject != null filters out nullish values (null and undefined) which don't have any properties. Without this check subject[methodName] could throw an error:

> TypeError: (undefined|null) has no properties

Checking for only a truthy value isn't enough, since 0 and "" are both falsy but do have properties.

After validating that subject is not nullish you can safely access the property and check if it matches typeof subject[methodName] == "function".


Applying this to your code you can now do:

if (hasMethod(me, "onChange")) {
  me.onChange(str);
}

Solution 27 - Javascript

    function sum(nb1,nb2){
       
       return nb1+nb2;
    }

    try{
      
      if(sum() != undefined){/*test if the function is defined before call it*/

        sum(3,5);               /*once the function is exist you can call it */

      }

    }catch(e){
      
      console.log("function not defined");/*the function is not defined or does not exists*/
    }

Solution 28 - Javascript

And then there is this...

( document.exitPointerLock || Function )();

Solution 29 - Javascript

Try this one:

Window.function_exists=function(function_name,scope){
//Setting default scope of none is provided
If(typeof scope === 'undefined') scope=window;
//Checking if function name is defined
If (typeof function_name === 'undefined') throw new 
Error('You have to provide an valid function name!');
//The type container
var fn= (typeof scope[function_name]);
//Function type
If(fn === 'function') return true;
//Function object type
if(fn.indexOf('function')!== false) return true; 
return false;
}

Be aware that I've write this with my cellphone Might contain some uppercase issues and/or other corrections needed like for example functions name

If you want a function like PHP to check if the var is set:

Window.isset=function (variable_con){
If(typeof variable_con !== 'undefined') return true;
return false;
}

Solution 30 - Javascript

To illustrate the preceding answers, here a quick JSFiddle snippet :

function test () {
console.log()

}

console.log(typeof test) // >> "function"

// implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as :
// var test = false
if(test){ console.log(true)}
else{console.log(false)}

// test by the typeof method
if( typeof test === "function"){ console.log(true)}
else{console.log(false)}


// confirm that the test is effective : 
// - entity with false value
var test2 = false
if(test2){ console.log(true)}
else{console.log(false)}

// confirm that the test is effective :
// - typeof entity
if( typeof test ==="foo"){ console.log(true)}
else{console.log(false)}

/* Expected :
function
true 
true 
false
false
*/

Solution 31 - Javascript

// just pass your tested function name instead of myFunctionName
if ( $.isFunction($.fn.myFunctionName) ) {
    console.log( 'write your code here.' );
}

Solution 32 - Javascript

This will verify if the function exists, if so it will be executed

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

Thus the error TypeError: me.onChange is not a function is prevent.

Solution 33 - Javascript

function isFunction( o ) { return null !== o && "function" === typeof o && !!o.apply; }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlec SmartView Question on Stackoverflow
Solution 1 - JavascriptAndrew HareView Answer on Stackoverflow
Solution 2 - JavascriptMisha NasledovView Answer on Stackoverflow
Solution 3 - JavascriptdavnicwilView Answer on Stackoverflow
Solution 4 - JavascriptNasser Al-WohaibiView Answer on Stackoverflow
Solution 5 - JavascriptdhulihanView Answer on Stackoverflow
Solution 6 - JavascriptSamir AlajmovicView Answer on Stackoverflow
Solution 7 - JavascriptMat CarlsonView Answer on Stackoverflow
Solution 8 - JavascriptTu4n3rView Answer on Stackoverflow
Solution 9 - JavascriptMuhammad TahirView Answer on Stackoverflow
Solution 10 - JavascriptLalnuntluanga ChhakchhuakView Answer on Stackoverflow
Solution 11 - JavascriptMiffTheFoxView Answer on Stackoverflow
Solution 12 - JavascriptAlexView Answer on Stackoverflow
Solution 13 - JavascriptMohammad LotfiView Answer on Stackoverflow
Solution 14 - JavascriptDavid DouglasView Answer on Stackoverflow
Solution 15 - JavascriptPandaWoodView Answer on Stackoverflow
Solution 16 - JavascriptSebastian HView Answer on Stackoverflow
Solution 17 - JavascriptLucas BustamanteView Answer on Stackoverflow
Solution 18 - JavascriptAylian CraspaView Answer on Stackoverflow
Solution 19 - JavascriptMatteus BarbosaView Answer on Stackoverflow
Solution 20 - JavascriptItay Moav -MalimovkaView Answer on Stackoverflow
Solution 21 - JavascriptwombletonView Answer on Stackoverflow
Solution 22 - Javascriptel DudeView Answer on Stackoverflow
Solution 23 - Javascriptmainak chakrabortyView Answer on Stackoverflow
Solution 24 - JavascriptAlexander FuchsView Answer on Stackoverflow
Solution 25 - JavascriptJulianView Answer on Stackoverflow
Solution 26 - Javascript3limin4t0rView Answer on Stackoverflow
Solution 27 - JavascriptIr CalifView Answer on Stackoverflow
Solution 28 - JavascriptMaster JamesView Answer on Stackoverflow
Solution 29 - JavascriptSkullWritterView Answer on Stackoverflow
Solution 30 - JavascriptHoCo_View Answer on Stackoverflow
Solution 31 - JavascriptZabid AhmedView Answer on Stackoverflow
Solution 32 - JavascriptnecrifedeView Answer on Stackoverflow
Solution 33 - JavascriptcskwgView Answer on Stackoverflow