Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for an empty map

Tags:

javascript

I'm having an interesting issue that I'm sure is easily explained, but the explanation is eluding me.

An undefined or null object in javascript is equal to false.

var x;
alert(!x); //returns true
alert(x==true); //returns false

What about an empty array object? Is that the equivalent of true or false?

var x = [];
alert (x==true); //returns false
alert (!x); //returns false

If it is equivalent to true, how do I check if it's non-empty? I was hoping to do

if (!x) {
    //do stuff
}

I tried checking x.length, but I'm using this object as a map:

var x = [];
alert(x.length); //returns 0
x.prop = "hello"; 
alert(x.length); //still returns 0

How can I check if my map is empty?

like image 815
chama Avatar asked Aug 21 '12 14:08

chama


2 Answers

It's not as easy as it looks, you have to check that the object has at least one property.

jQuery provides isEmptyObject for that purpose:

function isEmptyObject( obj ) {
    for ( var name in obj ) {
        return false;
    }
    return true;
}

Sample usage:

> var x = [];
> x.prop = "hello"; 
> isEmptyObject(x);
false
like image 100
João Silva Avatar answered Sep 20 '22 02:09

João Silva


Little confused as you seem to be mixing objects and arrays in your question. Hopefully this might help clear it up for you.

An empty array evaluates to true:

!![] //true

But integer 0 evaluates to false, so you can do:

!![].length //false

So:

if([].length) {
   //array has 1 element at least
} else {
  //array has 0 elements
}

However you do seem to be getting arrays and objects confused. In JavaScript, we have objects:

var x = {};
x.foo = "bar";
x.baz = 2;

And we have arrays:

var x = [];
x.push("foo");
x.length //1

You can't do what you do in your opener:

var x = []; //x is an array
x.foo = "bar"; //can't do this on an array
x.length; // 0 
like image 41
Jack Franklin Avatar answered Sep 24 '22 02:09

Jack Franklin