531

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;
}
4
  • 6
    Do you want to count the properties (this is what the code is doing) or just test whether the object is empty or not (this is stated in your question)? Commented Feb 14, 2011 at 15:59
  • 2
    Just as a recommendation of libraries that are capable of this is.js and lodash Commented Feb 12, 2015 at 10:02
  • For utilities like this, it is recommended to use some libraries out there. You could use lodash and use something like _.isEmpty(_.keys(yourObject)). And I believe you can now import those two methods individually, and not the whole lodash library. Commented Sep 28, 2018 at 18:20
  • Direct speed comparison here Commented Mar 27, 2023 at 9:11

23 Answers 23

650

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

Object.keys(obj).length === 0
Sign up to request clarification or add additional context in comments.

9 Comments

A more proper ES5 solution would be Object.getOwnPropertyNames(obj).length == 0 because Object.keys only gets the enumerable properties. In ES5 we have the power of defining property attributes, we could have an object with non-enumerable properties and Object.keys will just return an empty array... Object.getOwnPropertyNames returns an array containing all the own properties of an object, even if they aren't enumerable.
@CMS getOwnPropertyNames is recommended against by Crockford. According to him, this method was introduced to the language specifically for Caja (and other secure frameworks, I guess). So, there is a chance that this method is not or will not be available in certain environments.
This answer now works in all modern browsers; definitely the best one unless you need to support IE8-.
It's quite unbelievable that Object.isEmpty() isn't part of javascript yet
Semantically, I think, an object with zero enumerable properties should be considered "empty" (because unenumerable declared properties were probably meant to be "private"), so Object.keys.length is probably the right way to go.
|
463

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.

16 Comments

@frequent - var hasOwnProp would probably also work :-) We're looking to avoid as many lookups as possible (in case this is called in a place where performance kind of matters [if it really matters only profiling will tell you the fastest way on each platform]).
@NehaChoudhary - if you look at this jsFiddle you'll see the kind of situation this is designed to avoid.
I want to point out that this is much faster than the methods offered by ECMAScript5: jsperf.com/empty-object-comparisons.
Just a minor enhancement. The line: if (obj.length && obj.length > 0) return false; shouldn't be simply if (obj.length > 0) return false; ?
In livescript: has-own-property = Object.prototype.has-own-property is-empty-object = (o) -> unless o? then true if o.length > 0 then false if o.length is 0 then true for key of o if has-own-property.call o, key then return false return true
|
226
+50

EDIT: Note that you should probably use ES5 solution instead of this since ES5 support is widespread these days. It still works for jQuery though.


Easy and cross-browser way is by using jQuery.isEmptyObject:

if ($.isEmptyObject(obj))
{
    // do something
}

More: http://api.jquery.com/jQuery.isEmptyObject/

You need jquery though.

6 Comments

I'm amused that the jQuery option is the one that is "exemplary and worthy of an additional bounty", over a native ES5 solution. This answer is still useful in some cases, I suppose.
ES5 solution is not supported in all browsers (yet - at least AFAIK), so this solution makes sense if you are already using jQuery (which many sites are). Also, jQuery is a bit more efficient than Jakob's solution (not that it matters much in most cases though), as it doesn't traverse whole object before calculating the length - it returns false as soon as a key is found.
I doubt that's still true, if it ever was (the code is pretty standard) - but if you have an example and can validate on IE8, you should file a bug report with jQuery. They are pretty serious about that.
It's not cross browser since browsers do not include jQuery.
@Pier I feel like you're being intentionally obtuse here. Cross-browser doesn't indicate that it's included in the browser itself, merely that it works universally across the major accepted browsers.
|
101

Underscore and lodash each have a convenient isEmpty() function, if you don't mind adding an extra library.

_.isEmpty({});

5 Comments

Or for people who have already included underscore ;)
Late comment: as for 2016 you can use just lodash isEmpty (you don't need to import all the lodash, you can now import just a method from it, it was divided to multiple micro-packages in npm).
Yeah or you could import node_modules/* and ignore any dependency you take on any plugin </sarcasm>
The roll-your-own solutions are great for learning the intricacies of the language, but for production use it's best to leverage a robust library such as lodash. Lodash has been stress tested for both performance and corner cases. _.isEmpty() is convenient because it supports objects, arrays, just about anything.
You can also inspect the source and see if you need to import this: github.com/lodash/lodash/blob/4.17.14/lodash.js#L11479
69

Lets put this baby to bed; tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:

  • (for...in...) is the fastest option to use!
  • Object.keys(obj).length is 10 times slower for empty objects
  • JSON.stringify(obj).length is always the slowest (not surprising)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.

Bottom line performance wise, use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

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

Results under Node:

  • first result: return (Object.keys(obj).length === 0)
  • second result: for (var x in obj) { return false; }...
  • third result: for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }...
  • forth result: return ('{}' === JSON.stringify(obj))

Testing for Object with 0 keys 0.00018 0.000015 0.000015 0.000324

Testing for Object with 1 keys 0.000346 0.000458 0.000577 0.000657

Testing for Object with 2 keys 0.000375 0.00046 0.000565 0.000773

Testing for Object with 3 keys 0.000406 0.000476 0.000577 0.000904

Testing for Object with 4 keys 0.000435 0.000487 0.000589 0.001031

Testing for Object with 5 keys 0.000465 0.000501 0.000604 0.001148

Testing for Object with 6 keys 0.000492 0.000511 0.000618 0.001269

Testing for Object with 7 keys 0.000528 0.000527 0.000637 0.00138

Testing for Object with 8 keys 0.000565 0.000538 0.000647 0.00159

Testing for Object with 100 keys 0.003718 0.00243 0.002535 0.01381

Testing for Object with 1000 keys 0.0337 0.0193 0.0194 0.1337

Note that if your typical use case tests a non empty object with few keys, and rarely do you get to test empty objects or objects with 10 or more keys, consider the Object.keys(obj).length option. - otherwise go with the more generic (for... in...) implementation.

Note that Firefox seem to have a faster support for Object.keys(obj).length and Object.getOwnPropertyNames(obj).length, making it a better choice for any non empty Object, but still when it comes to empty objects, the (for...in...) is simply 10 times faster.

My 2 cents is that Object.keys(obj).length is a poor idea since it creates an object of keys just to count how many keys are inside, than destroys it! In order to create that object he needs to loop overt the keys... so why use it and not the (for... in...) option :)

var a = {};

function timeit(func,count) {
   if (!count) count = 100000;
   var start = Date.now();
   for (i=0;i<count;i++) func();
   var end = Date.now();
   var duration = end - start;
   console.log(duration/count)
}

function isEmpty1() {
    return (Object.keys(a).length === 0)
}
function isEmpty2() {
    for (x in a) { return false; }
    return true;
}
function isEmpty3() {
    for (x in a) { if (a.hasOwnProperty(x))  return false; }
    return true;
}
function isEmpty4() {
    return ('{}' === JSON.stringify(a))
}


for (var j=0;j<10;j++) {
   a = {}
   for (var i=0;i<j;i++) a[i] = i;
   console.log('Testing for Object with '+Object.keys(a).length+' keys')
   timeit(isEmpty1);
   timeit(isEmpty2);
   timeit(isEmpty3);
   timeit(isEmpty4);
}

a = {}
for (var i=0;i<100;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1);
timeit(isEmpty2);
timeit(isEmpty3);
timeit(isEmpty4, 10000);

a = {}
for (var i=0;i<1000;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1,10000);
timeit(isEmpty2,10000);
timeit(isEmpty3,10000);
timeit(isEmpty4,10000);

1 Comment

for (x in a) { return false; } can be a block-less single statement for statement. Meaning, you can save a stack block operation by removing the {}. Kindda, useless information. But might be noticeable with your 6-digit timing accuracy.
32

Elegant way - use keys

var myEmptyObj = {};
var myFullObj = {"key":"value"};
console.log(Object.keys(myEmptyObj).length); //0
console.log(Object.keys(myFullObj).length); //1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

6 Comments

Why has no one commented on this solution? Looks good to me.
@Vlad This is probably not very efficient. Why ask the JS engine to extract all the keys just to find out if there are any keys
@VictorGrazi is there any chance the engine might be storing all those keys in memory for easy reference already?
@adityamenon I would like to know the answer to that myself. Is it in the spec or does it vary between implementations?
This is 10 times slower for empty objects than using the (for... in) option - see performance tests above.
|
23
function isEmpty( o ) {
    for ( var p in o ) { 
        if ( o.hasOwnProperty( p ) ) { return false; }
    }
    return true;
}

3 Comments

@CMS Stupid IE :) At least IE9 corrected that.
@ŠimeVidas: In this solution, you declare p in your for... in loop with the var keyword. If you don't do this, does p become an implied global? Just wanted to ask about something that looks like a best practice.
@parisminton It does in the "default language". However, in strict mode (which is the recommended language), it throws a reference error (unless of course, there already exists a variable with that name in an outer scope). Therefore, you do want to put a var there.
22
var x= {}
var y= {x:'hi'}
console.log(Object.keys(x).length===0)
console.log(Object.keys(y).length===0)

true
false

http://jsfiddle.net/j7ona6hz/1/

Comments

19

Surprised to see so many weak answers on such a basic JS question... The top answer is no good too for these reasons:

  1. it generates a global variable
  2. returns true on undefined
  3. uses for...in which is extremely slow by itself
  4. function inside for...in is useless - return false without hasOwnProperty magic will work fine

In fact there's a simpler solution:

function isEmpty(value) {
    return Boolean(value && typeof value === 'object') && !Object.keys(value).length;
}

3 Comments

I think it's ok to return false on undefined, since undefined is not an object.
This is 10 times slower for empty objects than using the (for... in) option - see performance tests above.
In my opinion, this question isn't too basic: because "emptiness" is a very multifaceted thing in javascript - depending on what type of value we're dealing with, we have different conceptions of "emptiness". An Array is empty when it has no items. Even if I say let a = []; a.v = 'hello';, most people will agree a is "empty". But an Object is empty if it has no properties. Even if we do let o = { length: 0 };, most people will agree (I think) that o isn't empty because it has a "length" property.
11

https://lodash.com/docs#isEmpty comes in pretty handy:

_.isEmpty({})   // true
_.isEmpty()     // true
_.isEmpty(null) // true
_.isEmpty("")   // true

Comments

7

How bad is this?

function(obj){
    for(var key in obj){
        return false; // not empty
    }

    return true; // empty
}

1 Comment

Actually - this is very good - see performance testing above...
4

No need for a library.

function(){ //must be within a function
 var obj = {}; //the object to test

 for(var isNotEmpty in obj) //will loop through once if there is a property of some sort, then
    return alert('not empty')//what ever you are trying to do once

 return alert('empty'); //nope obj was empty do this instead;
}

Comments

4

It might be a bit hacky. You can try this.

if (JSON.stringify(data).length === 2) {
   // Do something
}

Not sure if there is any disadvantage of this method.

5 Comments

If data isn't an object, this could give a false positive for JSON.stringify([]) or JSON.stringify("") or JSON.stringify(42). That's all I've got though.
also, I think performance could be worse than using some other method. And JSON.stringify is not available in every browser
+1 Excellent answer + this is blazing fast solution !!! Ignore the other comments if your application points to modern web browser engines.
-1 An overkill for most cases. @cept0 How stringifing an object may be blazing fast?!
If you like this solution, a tweak like this makes it more explicit. JSON.stringify({}) === "{}"
1

fast onliner for 'dictionary'-objects:

function isEmptyDict(d){for (var k in d) return false; return true}

2 Comments

I think this will have better performance: isEmpty = function(a,b){for(b in a){break}return !b};
I do not see why break, return !b would be better than return false/return true? break and !b both require an extra 'operation'. Minor detail is that b should not be an input variable, but defined inside the function; for (var b in a)... does this, even if a is 'empty'
1

You can write a fallback if Array.isArray and Object.getOwnPropertyNames is not available

XX.isEmpty = function(a){
    if(Array.isArray(a)){
        return (a.length==0);
    }
    if(!a){
        return true;
    }
    if(a instanceof Object){

        if(a instanceof Date){
            return false;
        }

        if(Object.getOwnPropertyNames(a).length == 0){
            return true;
        }
    }
    return false;
}

Comments

1

Imagine you have the objects below:

var obj1= {};
var obj2= {test: "test"};

Don't forget we can NOT use === sign for testing an object equality as they get inheritance, so If you using ECMA 5 and upper version of javascript, the answer is easy, you can use the function below:

function isEmpty(obj) {
   //check if it's an Obj first
   var isObj = obj !== null 
   && typeof obj === 'object' 
   && Object.prototype.toString.call(obj) === '[object Object]';

   if (isObj) {
       for (var o in obj) {
           if (obj.hasOwnProperty(o)) {
               return false;
               break;
           }
       }
       return true;
   } else {
       console.error("isEmpty function only accept an Object");
   }
}

so the result as below:

isEmpty(obj1); //this returns true
isEmpty(obj2); //this returns false
isEmpty([]); // log in console: isEmpty function only accept an Object

Comments

1
funtion isEmpty(o,i)
{
    for(i in o)
    {
        return!1
    }
    return!0
}

2 Comments

works for my 99% cases.
The !0 and !1 are rather confusing here. Why not just simply true and false?
0

here's a good way to do it

function isEmpty(obj) {
  if (Array.isArray(obj)) {
    return obj.length === 0;
  } else if (typeof obj === 'object') {
    for (var i in obj) {
      return false;
    }
    return true;
  } else {
    return !obj;
  }
}

Comments

0
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isArray(a) {
    return Object.prototype.toString.call(a) === '[object Array]'
}
function isObject(a) {
    return Object.prototype.toString.call(a) === '[object Object]'
}
function isEmpty(a) {
    if (null == a || "" == a)return!0;
    if ("number" == typeof a || "string" == typeof a)return!1;
    var b = !0;
    if (isArray(a)) {
        if (!a.length)return!0;
        for (var c = 0; c < a.length; c++)isEmpty(a[c]) || (b = !1);
        return b
    }
    if (isObject(a)) {
        for (var d in a)hasOwnProperty.call(a, d) && (isEmpty(a[d]) || (b = !1));
        return b
    }
    return!0
}

Comments

0

May be you can use this decision:

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

Comments

0

I modified Sean Vieira's code to suit my needs. null and undefined don't count as object at all, and numbers, boolean values and empty strings return false.

'use strict';

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

var isObjectEmpty = function(obj) {
    // null and undefined are not empty
    if (obj == null) return false;
    if(obj === false) return false;
    if(obj === true) return false;
    if(obj === "") return false;

    if(typeof obj === "number") {
        return false;
    }   
    
    // 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;

    // 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;
};

exports.isObjectEmpty = isObjectEmpty;

Comments

-1

here my solution

function isEmpty(value) {
    if(Object.prototype.toString.call(value) === '[object Array]') {
        return value.length == 0;
    } else if(value != null && typeof value === 'object') {
        return Object.getOwnPropertyNames(value).length  == 0;
    } else {
        return !(value || (value === 0));
    }
}

Chears

Comments

-2
if (Object.getOwnPropertyNames(obj1).length > 0)
{
 alert('obj1 is empty!');
}

2 Comments

Shouldn't the logic be reversed?
Yes, more correct would be Object.getOwnPropertyNames(obj1).length < 1. Answer as written doesn't work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.