Sometimes, we want to check if anonymous object has a method with JavaScript.
In this article, we’ll look at how to check if anonymous object has a method with JavaScript.
How to check if anonymous object has a method with JavaScript?
To check if anonymous object has a method with JavaScript, we can check with the typeof
operator.
For instance, we write
const myObj = {
prop1: "no",
prop2() {
return false;
},
};
if (typeof myObj.prop2 === "function") {
console.log("It's a function");
} else if (typeof myObj.prop2 === "undefined") {
console.log("It's undefined");
} else {
console.log("It's neither undefined nor a function");
}
to define the myObj
object.
Then we check if myObj.prop2
is a function with the typeof
operator.
To check if it’s a function, we write
typeof myObj.prop2 === "function"
to check if prop2
is a function.
Conclusion
To check if anonymous object has a method with JavaScript, we can check with the typeof
operator.