How can you perform a JavaScript check if function exists before calling it to avoid runtime errors like 'is not a function'?

Hi peeps!

I have a setup where I retrieve an object differently depending on the browser:

function getID(swfID) {
if (navigator.appName.indexOf("Microsoft") !== -1) {
me = window[swfID];
} else {
me = document[swfID];
}
}
Then, I try to call a method on that object:

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

The problem is that onChange isn’t always available, and I get me.onChange is not a function errors in Firebug. I want to fail gracefully since this feature isn’t critical. But using typeof me.onChange === 'function' still throws an error.

What’s the most reliable way in JavaScript to check if a function exists on an object before calling it, preferably without resorting to try/catch?

Thank you in advance :-))

Hi @kusha.kpr!

Jumping right into your question about safely checking properties or methods on objects in JavaScript. Ah, this is a classic case that many new (and even experienced!) JS developers encounter!

The issue here is likely that me is undefined when you try to check me.onChange, so even typeof me.onChange throws an error because you’re essentially trying to access a property on an undefined value (undefined.onChange).

The best way to handle this is to first check that me itself exists before attempting to check its method:

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

This two-part check (me && ...) ensures me isn’t null or undefined before trying to access a method on it. You actually don’t need a try/catch block for this specific scenario!

Hope you find this helpful! :innocent:

Hey there @kusha.kpr! Totally understand that frustrating scenario with undefined objects in JavaScript,been there myself!

What @joe-elmoufak suggested would also work but always having something up your sleeve doesn’t hurt right?

You’re spot on: when you do just typeof me.onChange === 'function' and me is undefined, JavaScript will indeed “freak out” and throw an error. The safest and most modern pattern to handle this involves optional chaining (?.):

if (me?.onChange instanceof Function) {
  me.onChange(str);
}

That optional chaining (?.) is super handy here. It’ll gracefully return undefined if me doesn’t exist (or is null), and then the instanceof Function check determines if the method is actually a function. It’s wonderfully clean, truly modern, and prevents those unexpected crashes.

Hope the solution provides you the help you needed!

Hello @kusha.kpr, @richaaroy and @joe-elmoufak Adding another layer to the discussion on securely checking object methods after the excellent points already raised.

I’ve definitely been burned by this too! The key, as you’ve identified, is to proactively validate before acting. My usual approach is similar to the first pattern discussed:

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

However, if you’re working in ES2020+ environments, optional chaining (?.) combined with a function check is my absolute go-to for maximum conciseness and safety:

JavaScriptme?.onChange?.(str);

That’s arguably the shortest and cleanest way to handle it. It’ll safely attempt to call the onChange function only if both me and onChange exist and onChange is indeed callable. No crashes, just clean flow!

Hope you find this of your use!