Check if an Object contains a Function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

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.

If the equality check in our if statement passes, then 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 of the operator is always wrapped in a string.

The typeof operator returns the string function for both arrow and named functions.

index.js
console.log(typeof (() => {})); // 👉️ function console.log(typeof function () {}); // 👉️ function

Technically, the type of a class is also a function.

index.js
console.log(typeof class A {}); // 👉️ function

Classes are just syntactic sugar for functions in JavaScript.

However, we can't have a class as a property in an object, so our solution works just fine.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.