Here we can see which types of objects in JavaScript/ECMAScript evaluate to false
.
My question is: if a variable evaluates to true
, is it guaranteed to have a hasOwnProperty
method?
In other words, is the following test safe?
if (bar && bar.hasOwnProperty("foo")) { ... }
My goal is to prevent exceptions like Cannot read property 'hasOwnProperty' of null
.
My application scenario: in an AngularJS $http
service error handler I want to be prepared for all situations. This is a little difficult for me, because I am not tremendously experienced with JavaScript and the different situations in which this error handler might be called can not easily be tested for. The error handler function has the following signature:
function(data, status, headers, config) {}
In the function body I evaluate data
like so:
if (data && data.hasOwnProperty("error")) {
alert(data.error);
}
Does this look safe to you under all circumstances? Safe in the sense that this test does not throw an exception, no matter how AngularJS actually calls the error handler.