I seem to be using this test a lot
if( object && object !== "null" && object !== "undefined" ){ doSomething(); }
on objects
I get back from a service call or from reading cookies (since different browsers return the different values null
, undefined
, "null"
, or "undefined"
).
Is there an easier/more efficient way of doing this check?
Use the in operator The in operator returns true if a property exists in an object. If a property does not exist in the object, it returns false . Unlike the hasOwnProperty() method, the in operator looks for the property in both own properties and inherited properties of the object.
typeof null evaluates to 'object' , thus the correct way to use typeof to detect an object is typeof object === 'object' && object !== null . instanceof operator let's identify the instance's constructor. object instanceof Constructor evaluates to true if object is an instance of Constructor .
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
I don't think you can make that any simpler, but you could certainly refactor that logic into a function:
function isRealValue(obj) { return obj && obj !== 'null' && obj !== 'undefined'; }
Then, at least your code becomes:
if (isRealValue(yourObject)) { doSomething(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With