Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript test ( object && object !== "null" && object !== "undefined" )

Tags:

javascript

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?

like image 392
Nick G. Avatar asked Sep 21 '12 17:09

Nick G.


People also ask

How do you check if something is in an object?

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.

How can you tell if a object is typeof?

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 .

How do you check if an object has a key in JavaScript?

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.


1 Answers

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(); } 
like image 83
aquinas Avatar answered Oct 03 '22 22:10

aquinas