42

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?

3 Answers 3

82

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!
}
Sign up to request clarification or add additional context in comments.

4 Comments

How would this work for a jQuery plugin? like $.fn.mask?
What about if I want to allow my function to pass window in string format too? load.js("script.js", function() {}, "window.myCallbackFn");
Doesn't work when you don't have a window object, like with node.
Can you use this instead of window? Will that work in node and a browser? Or would if (typeof (window || this)[strOfFunction] === "function") { /* ... */ } be better form?
8

You can use eval:

if ( eval("typeof stringFunction === 'function'") ){ /*whatever*/ }

4 Comments

The use of eval should never be taken lightly. One needs to understand the implications of using it. See Eval is Evil and Eval isn't evil, just misunderstood.
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...
Literally always some guy has to point out that "eval is evil". Using eval is fine if you know what you're doing.
Yes, I love eval. Eval is the angel
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.