In this article, we will cover how to check if a JavaScript object contains a function as one of its properties. To achieve this, we will use the `typeof` operator on the object property and check if it returns a string result that is equal to `function`.
First, let’s create an object and initialize it with a function property –
const obj = {
doSomething: () => {
return"Something";
}
};
Then, we need to check using an `if` condition if `doSomething` property is a function using the `typeof` operator. We will print some string on the console that indicates whether the property is a function or not.
if (typeof obj.doSomething === "function")
console.log("Property is a function");
else console.log("Property is not a function");
If we check our console, we will see that we got “Property is a function” printed as output since `doSomething` property matched the type `function`.
Now, let’s add another property to `obj` that is not of function type and do the check –
const obj = {
notFunction: "I am a string",
doSomething: () => {
return"Something";
}
};
Then, we will pass `notFunction` property to our `if` statement and check the output on the console.
if (typeof obj.notFunction === "function")
console.log("Property is a function");
else console.log("Property is not a function");
As we can see, since the property `notFunction` is of type string, it did not pass the condition in our `if` statement.
Finally, we can wrap this logic into a function so that we can apply it to any property –
const propertyIsFunction = (property) => {
if (typeof property === "function") return true;
else return false;
};
Now let’s pass `doSomething` property to this function and display our output on the console. We will use the `?` ternary operator to wrap this in few lines of code –
propertyIsFunction(obj.doSomething)
? console.log("Property is a function")
: console.log("Property is not a function");