Check if an Object contains a Function in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20211 min read

banner

Photo by Kylo

Check if an Object contains a Function #

Use the typeof operator to check if an object contains a function, e.g. typeof obj.sum === 'function'. The typeof operator returns a string that indicates the type of the value. For functions, the operator returns a string containing the word function.

index.js
const obj = { sum: (a, b) => { return a + b; }, }; if (typeof obj.sum === 'function') { console.log('โœ… the sum property points to a function'); } else { console.log("โ›”๏ธ the sum property DOESN'T point to a function"); } console.log(typeof obj.sum); // ๐Ÿ‘‰๏ธ "function" console.log(typeof obj.doesNotExist); // ๐Ÿ‘‰๏ธ "undefined"

We used the typeof operator to check if the sum property of the object points to a function.

The typeof operator returns a string containing the type of the value to the right.

If the equality check in our if statement passes, we can conclude that the property on the object points to a function.

Here are some more examples of using the typeof operator.

index.js
console.log(typeof {}); // ๐Ÿ‘‰๏ธ "object" console.log(typeof []); // ๐Ÿ‘‰๏ธ "object" console.log(typeof null); // ๐Ÿ‘‰๏ธ "object" console.log(typeof (() => {})); // ๐Ÿ‘‰๏ธ "function" console.log(typeof ''); // ๐Ÿ‘‰๏ธ "string" console.log(typeof 0); // ๐Ÿ‘‰๏ธ "number" console.log(typeof NaN); // ๐Ÿ‘‰๏ธ "number" console.log(typeof undefined); // ๐Ÿ‘‰๏ธ "undefined"
Note that the return value from the operator is always wrapped in a string.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee