How to check if function exists in JavaScript?

How to check if function exists in JavaScript?

Try something like this:

if (typeof me.onChange !== undefined) { 
    // safe to use the function

or better yet (as per UpTheCreek upvoted comment)

if (typeof me.onChange === function) { 
    // safe to use the function

I had this problem.

if (obj && typeof obj === function) { ... }

kept throwing a reference error if obj happened to be undefined.

In the end I did the following:

if (typeof obj !== undefined && typeof obj === function) { ... }

A colleague pointed out to me that checking if its !== undefined and then === function is redundant of course.


if (typeof obj === function) { ... }

Much cleaner and works great.

How to check if function exists in JavaScript?

Modern JavaScript to the rescue!

In 2021, this is solved* in JavaScript (and TypeScript) with the new Optional Chaining syntax.


If onChange exists, it gets called.

If onChange does not exist, nothing happens: the expression returns undefined.

So for let value = me.onChange?.(str), value will be undefined if onChange does not exist.

Note, if onChange exists but is not a function, it throws a TypeError just the same as if you call any non-function as a function. Optional Chaining doesnt do any magic to make this go away.

* Optional Chaining is a stage 4 TC39 proposal, meaning its not officially in the ECMAScript spec yet, but is essentially guaranteed to be included in the next version. You can use it today via Babel or TypeScript with confidence the syntax wont change.

Leave a Reply

Your email address will not be published.