How to check if function exists in JavaScript?
I had this problem. if (obj && typeof obj === 'function') { ... }
kept throwing a reference error if obj
happened to be undefined
, so in the end I did the following:
if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }
However, a colleague pointed out to me that checking if it's !== 'undefined'
and then === 'function'
is redundant, thus:
Simpler:
if (typeof obj === 'function') { ... }
Much cleaner and works great.
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
}