Dylan
Dylan

Reputation: 9383

check if a function exists with its name in a string?

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?

Upvotes: 42

Views: 26747

Answers (3)

Itaca
Itaca

Reputation: 47

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.

Upvotes: 0

Fredius
Fredius

Reputation: 175

You can use eval:

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

Upvotes: 8

Matt
Matt

Reputation: 75327

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!
}

Upvotes: 82

Related Questions