It is a very common requirement that is needed by many JavaScript developers to check if an object is empty in JavaScript without having to write more than one line of code. In the old days, you usually had to make the following for … loop in a common function isEmpty in order to check if the object is empty:
function isEmpty(myObject) { for(var key in myObject) { if (myObject.hasOwnProperty(key)) { return false; } } return true; }
Thanks to ECMAScript 5, you can now just use the Object.keys() function to check the object keys, so you can check if the myObject (for example) is empty as follows:
Object.keys(myObject).length == 0
That is NOT faster. It is less code.
The isEmpty loop is O(1).
Object.keys is O(n) in time and memory.
See performance tests here. isEmpty is faster EVEN when the objects are all empty:
http://jsperf.com/empty-object-tests/3
Our discussion of this on reddit is here:
http://www.reddit.com/r/javascript/comments/1e2f7m/fast_checking_for_empty_objects_in_javascript/
@Scrogu: Great Comment.
However, I did not mean: “Fast in performance”, I mean “Fast in checking from the effort perspective”.
Thanks a lot for the notice regarding performance.
Keep in mind that this is not supported in IE8. You might need a need a polyfill go cover those bases.