How to Test if a Function Exists in Javascript

I’m no Javascript expert and I couldn’t work out why it seemed to be so difficult to test to see if a function existed before I called it. In the end Google provided a better way though it wasn’t the most popular suggestion out there, to me it seems the most sensible way:

    if (window.myFunctionName) {
        myFunctionName();
    }

Where myFunctionName is the function you’re testing for, of course.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s