Fast checking for Empty Objects in JavaScript

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

3 thoughts on “Fast checking for Empty Objects in JavaScript

  1. @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.

Leave a Reply to Hazem Saleh Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Warning: fsockopen() [function.fsockopen]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/83/10439583/html/wp-content/plugins/sweetcaptcha-revolutionary-free-captcha-service/library/sweetcaptcha.php on line 71

Warning: fsockopen() [function.fsockopen]: unable to connect to www.sweetcaptcha.com:80 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in /home/content/83/10439583/html/wp-content/plugins/sweetcaptcha-revolutionary-free-captcha-service/library/sweetcaptcha.php on line 71
Couldn't connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0)