Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty JS Object

Is there a better way to check if an object is empty? I'm using this:

function isObjEmpty(obj)
{
    for (var p in obj) return false;
    return true;
}
like image 969
Rodrigo Manguinho Avatar asked May 07 '12 13:05

Rodrigo Manguinho


2 Answers

If you're looking for a one-liner, consider Object.keys:

var isEmpty = !Object.keys(obj).length;

Your current method is dangerous, since it will always return false when Object.prototype has been extended: http://jsfiddle.net/Neppc/

like image 71
Rob W Avatar answered Nov 09 '22 06:11

Rob W


Another option is built into jQuery: jQuery.isEmptyObject(obj)

Edit: Interestingly, that implementation is the same as your code in the question.

like image 25
Eric Brenden Avatar answered Nov 09 '22 04:11

Eric Brenden