To check if a property exists, you can just write if(x in options)...
Libraries exist to make tedious or difficult operations simple, This is such a simple operation that no library is needed and you'd be unlikely to find it added to a library.
While .hasOwnProperty()
can work, it will only test for properties attached directly to the object in quesiton, while the in
approach tests for inherited properties as well.
But, be careful about throwing errors. It's not generally something that you want to do for performance reasons. It's better to return a code or message.
var options = {
foo:42,
bar:"doesn't matter"
};
function propTest(propName, obj){
// Instead of throwing an error, return a value that indicates success or not
return (propName in obj) ? true : false;
}
console.log(propTest("foo", options));
console.log(propTest("bar", options));
console.log(propTest("baz", options));