In JavaScript, a method is a JavaScript object property that has a function as its value.
Sometimes, we want to check if an object property is a method.
In this article, we’ll look at how to check if a JavaScript object property is a method.
Use the typeof Operator
We can use the typeof
operator to check if an object property is a method.
If an object property is a method, then the typeof
operator should return 'function'
.
For instance, we can write:
const obj = {
prop1: 'no',
prop2() {
return false;
}
}
console.log(typeof obj.prop2 === 'function');
to check if obj.prop2
is a method.
If it’s a method, then typeof obj.prop2
should return 'function'
.
The console log logs true
, so we know obj.prop2
is a method.
If it’s not a method or it doesn’t exist, then typeof obj.prop2
won’t return 'function'
.
Conclusion
We can use the typeof
operator to check if an object property is a method.