29

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?

Nick G.
  • 1,145
  • 2
  • 10
  • 19
  • 3
    If it actually may have the string values `"null"` and `"undefined"`, then your method can't be any simpler. – Fabrício Matté Sep 21 '12 at 17:36
  • It does sometimes have the strings `"null"` or `"undefined"`. Thanks for the confirmation. – Nick G. Sep 21 '12 at 17:41
  • You can also use `!!` like `if(!!myobj){doSomething();}` to check the object. It converts the object to boolean and then inverts it again. Look at [this](http://stackoverflow.com/a/10597474) answer for a very good explanation . – A J Qarshi Nov 05 '15 at 11:31

11 Answers11

40

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();
}
John
  • 1
  • 13
  • 98
  • 177
aquinas
  • 23,318
  • 5
  • 58
  • 81
11

If you have jQuery, you could use $.isEmptyObject().

$.isEmptyObject(null)
$.isEmptyObject(undefined)
var obj = {}
$.isEmptyObject(obj)

All these calls will return true. Hope it helps

Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 11
    Don't answer JavaScript questions with jQuery. jQuery isn't backwards compatible with JavaScript, it constantly changes breaking things posted, you save 1KB here or there by dumping 70KB on the client when their browser can already handle *real* JavaScript and it has horrible performance compared to knowing how to program competently. – John Jul 26 '16 at 18:21
5
if(!!object){
  doSomething();
}
Sean Bradley
  • 3,254
  • 1
  • 17
  • 10
4

If object is truthy, we already know that it is not null or undefined (assuming that the string values are a mistake). I assume that a not null and not undefined test is wanted.

If so, a simple comparison to null or undefined is to compare != null.

if( object != null ){
    doSomething();
}

The doSomething function will run only if object is neither null nor undefined.

scatter
  • 59
  • 1
  • No: "It does sometimes have the strings "null" or "undefined"." This won't work if the value has a REAL string in it: http://jsfiddle.net/7eYKN/1/ – aquinas Sep 21 '12 at 17:53
  • @aquinas: I saw that comment under the question, but didn't have enough rep to reply. The question would be then what is meant by "sometimes". I think the asker is giving us some impressionistic code instead of actual representation of code. Yes, a person may sometimes want to compare to the `"null"` string, but that's hardly a common scenario, but it is more common to see the `"undefined"` string because of `typeof foo === "undefined"`. So my answer tries to get at the core of what is usually wanted since the question doesn't seem to represent any common real world example. – scatter Sep 21 '12 at 17:56
  • @aquinas: If I had more rep, I'd also comment that SnakeEyes code will always give a `true` result. – scatter Sep 21 '12 at 17:58
  • Oh, I missed that about the cookies. Must be a stringified value. I think your answer to DRY it with a function is probably the best solution if that's the issue. – scatter Sep 21 '12 at 18:02
4

Maybe like this:

var myObj = {};
var isEmptyObj = !Object.keys(myObj).length;

if(isEmptyObj) {
    // true
} else {
AndriyFM
  • 1,389
  • 14
  • 11
2

maybe like this

   if (typeof object !== "undefined" || object !== null)
    // do something
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • This isn't equivalent to the original function is it? He is specifically checking for a string with the value of "null". See: http://jsfiddle.net/7eYKN/ – aquinas Sep 21 '12 at 17:46
  • object is not a reserved word. – jbabey Sep 21 '12 at 17:48
  • @SnakeEyes - That link you posted is terrible... not sure where they got their information from! Half of the words listed are not reserved words, and some of them are but are listed wrongly (e.g. `instanceOf` instead of `instanceof`). I'd stay away from that site if I were you. – James Allardice Sep 21 '12 at 17:50
  • @JamesAllardice then I will make mymown list of js reserved keywords using best books. :) – Snake Eyes Sep 21 '12 at 17:51
  • @SnakeEyes - See the link to the spec in my first comment. That contains the actual official list of reserved words! – James Allardice Sep 21 '12 at 17:52
2

This should work without any issue.

if(object){ // checks for null and undefined
    doSomething();
}
Sampath
  • 63,341
  • 64
  • 307
  • 441
1

The best way to check if an object is empty is by using a utility function like the one below.

create a function

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

Use above function following way:-

So if you have an empty object, you can check whether it is empty by using the above function.

var myObj = {}; // Empty Object
if(isEmpty(myObj)) {
    // Object is empty (Would return true in this example)
} else {
    // Object is NOT empty
}
Harish Mahajan
  • 3,254
  • 4
  • 27
  • 49
0

I think you could simplify a bit your logic with the following:

if (object != null && typeof(object) == "object") {
    doSomething();
}

The main problem is that if you just check typeof(object) == "object", it will return true if object is null since null's type is "object". However, if you first check that object != null, you can be sure you are having something that is neither undefined nor null.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
0

another simple way is

if (eval(object)) doSomething();

You can use eval to cast any type including string and be executed by javascript, here is eval documentation

0

If you want an Object, that is not an Array, and is not null, you might have to do some work, as all 3 will have the same typeof value.

if (
  typeof maybeObject === 'object' 
  && maybeObject !== null 
  && !Array.isArray(maybeObject)) {
}
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78