[ACCEPTED]-Check for an empty map-javascript

Accepted answer
Score: 14

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

jQuery 1 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
Score: 7

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

An empty 6 array evaluates to true:

!![] //true

But integer 0 evaluates 5 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 4 seem to be getting arrays and objects confused. In 3 JavaScript, we have objects:

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

And we have 2 arrays:

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

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

var x = []; //x is an array
x.foo = "bar"; //can't do this on an array
x.length; // 0 
Score: 4

if you are using JQuery

jQuery.isEmptyObject(obj)

If not, u can implement 1 your own

isEmptyObject = function(obj) {
for (key in obj) {
    if (obj.hasOwnProperty(key)) return false;
}
return true;
};
Score: 3

If you're using a Proper JS Map<K, V> Object, you 4 can simply use the Map API on Mozilla Docs.

Specifically 3 there is a Map.prototype.size property, as well as Map.prototype.entries() method, which 2 I believe returns an Array [] of keys. If 1 that is length 0 then the map is empty.

Score: 2

First of all, you are using an Array not 4 a map. A map would be an Object instance:

var x = {};
x.prop = "5";

Your 3 code is valid since Arrays are also Objects. You 2 can check if your Object is empty as answered 1 in this question.

Score: 0

*If of an empty list will give true (if (array1)).

*x.prop does 5 not really add any elements to the array, it 4 just assigns value "hello" to property x 3 of the array but the array is still empty. So 2 you should still use .length to check is array 1 is empty.

Score: 0

For the Map object, use size:

let map = new Map()
console.log(map.size == 0) // true
map.set(['gari','baldi'])
console.log(map.size == 0) // false

0

More Related questions