41

I create functions in Javascript dynamically. Sometimes I need to check if a certain function is actually already created.

I have the name of the function as a string. How can I check whether a function exists based on a given value in a string?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Dylan
  • 9,129
  • 20
  • 96
  • 153

3 Answers3

81

You can check whether it's defined in the global scope using;

if (typeof window[strOfFunction] === "function") {
    // celebrate
    //window[strOfFunction](); //To call the function dynamically!
}
Vikas
  • 24,082
  • 37
  • 117
  • 159
Matt
  • 74,352
  • 26
  • 153
  • 180
8

You can use eval:

if ( eval("typeof stringFunction === 'function'") ){ /*whatever*/ }
Fredius
  • 175
  • 1
  • 4
  • 4
    The use of `eval` should never be taken lightly. One needs to understand the implications of using it. See [Eval is Evil](http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx) and [Eval isn't evil, just misunderstood](http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/). – Jason Aller Apr 15 '14 at 19:07
  • 2
    You can use eval() for many things but you should really only use it if you have no other alternative. It is handy to be able to just slap a string together and get it to evaluate. if ( eval("typeof stringFunction === 'function'") ){ /*whatever*/ } IMHO should be eval("answer = typeof stringFunction === 'function'"); if ( answer ){ /*whatever*/ } Some funny stuff is happening with things like with, eval, this, and some muppet theory regarding the use of "use strict"; to help improve coding, fine if you are going to make it a compiled language but JS isn't... – Mark Giblin Jan 19 '15 at 11:39
  • 1
    Literally always some guy has to point out that "eval is evil". Using eval is fine if you know what you're doing. – Vidar Sep 14 '18 at 23:17
  • Yes, I love eval. Eval is the angel – Arash Sep 26 '20 at 12:11
0

We're adding our 2 cents because the accepted answer is right, but benefits from a little clarification:

window["myFunctionNameHere"] is one simple way to solve the problem, but basically considering window as any global object accessible in the desired scope. Additionally, you must be sure to actually ASSIGN the function properly in such scope, of course.

In the case of window, for example, you'll first need

<script>
    $(document).ready(function () {
        window.myFunctionNameHere = function() {
            console.log('Hello world');
        }
    });
</script>

After this, the

typeof window["myFunctionNameHere"] === "function"

Will work as expected.

Itaca
  • 39
  • 6