Categories
JavaScript Answers

How to check if anonymous object has a method with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *