TheRealFakeNews
TheRealFakeNews

Reputation: 8173

Checking if a function is of type Function in javascript

Yes, I know there are plenty of posts on this, but I do not understand the selected answer of this post. Particularly, why is it necessary to return object?

Why wouldn't something like Object.prototype.toString.call(myFunc) be sufficient as described by MDN?

Upvotes: 0

Views: 53

Answers (2)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19110

return object && getClass.call(object) == '[object Function]'

This construction simply verifies if object is not null or undefined (generally falsy).
This way it's faster, because JavaScript doesn't evaluate the getClass() call on a falsy object.

Upvotes: 0

Bergi
Bergi

Reputation: 665040

why is it necessary to return object?

It's not necessary to do object &&, but a shortcut for falsy values that avoids the method call for values such as null. Of course, if you're looking for speed, you probably should go for typeof object == "function"

Why wouldn't something like Object.prototype.toString.call(myFunc) be sufficient?

It is sufficient.

Upvotes: 1

Related Questions