Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is object empty? [duplicate]

Tags:

javascript

What is the fastest way to check if an object is empty or not?

Is there a faster and better way than this:

function count_obj(obj){     var i = 0;     for(var key in obj){         ++i;     }      return i; } 
like image 429
clarkk Avatar asked Feb 14 '11 15:02

clarkk


People also ask

Is Empty object True or false?

The empty object is not undefined. The only falsy values in JS are 0 , false , null , undefined , empty string, and NaN .

Is Empty object truthy in JavaScript?

There are only seven values that are falsy in JavaScript, and empty objects are not one of them. An empty object is an object that has no properties of its own. You can use the Object.

Does object values create a copy?

One of the fundamental differences of objects versus primitives is that objects are stored and copied “by reference”, whereas primitive values: strings, numbers, booleans, etc – are always copied “as a whole value”.


2 Answers

For ECMAScript5 (not supported in all browsers yet though), you can use:

Object.keys(obj).length === 0 
like image 162
Jakob Avatar answered Nov 10 '22 05:11

Jakob


I'm assuming that by empty you mean "has no properties of its own".

// Speed up calls to hasOwnProperty var hasOwnProperty = Object.prototype.hasOwnProperty;  function isEmpty(obj) {      // null and undefined are "empty"     if (obj == null) return true;      // Assume if it has a length property with a non-zero value     // that that property is correct.     if (obj.length > 0)    return false;     if (obj.length === 0)  return true;      // If it isn't an object at this point     // it is empty, but it can't be anything *but* empty     // Is it empty?  Depends on your application.     if (typeof obj !== "object") return true;      // Otherwise, does it have any properties of its own?     // Note that this doesn't handle     // toString and valueOf enumeration bugs in IE < 9     for (var key in obj) {         if (hasOwnProperty.call(obj, key)) return false;     }      return true; } 

Examples:

isEmpty(""), // true isEmpty(33), // true (arguably could be a TypeError) isEmpty([]), // true isEmpty({}), // true isEmpty({length: 0, custom_property: []}), // true  isEmpty("Hello"), // false isEmpty([1,2,3]), // false isEmpty({test: 1}), // false isEmpty({length: 3, custom_property: [1,2,3]}) // false 

If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames instead of the hasOwnProperty loop:

if (Object.getOwnPropertyNames(obj).length > 0) return false; 

This will ensure that even if the object only has non-enumerable properties isEmpty will still give you the correct results.

like image 43
Sean Vieira Avatar answered Nov 10 '22 05:11

Sean Vieira