The Easiest way to check 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

I wish that this tip can be useful for you.

This entry was posted in JavaScript and tagged , , , , , , , , by Hazem Saleh. Bookmark the permalink.

About Hazem Saleh

Hazem Saleh has more than eleven years of experience in Cloud, Mobile and Open Source technologies. He worked as a software engineer, technical leader, application architect, and technical consultant for many clients around the world. He is an Apache PMC (Project Management Committee) member and a person who spent many years of his life writing open source software. Beside being the author of the "JavaScript Unit Testing" book, "JavaScript Mobile Application Development" book, "Pro JSF and HTML5" book and the co-author of the "Definitive guide to Apache MyFaces" book, Hazem is also an author of many technical articles, a developerWorks contributing author and a technical speaker in both local and international conferences such as ApacheCon North America, Geecon, JavaLand, JSFDays, CON-FESS Vienna and JavaOne. Hazem is an XIBMer, he worked in IBM for ten years. Now, He is working for Nickelodeon New York as a Mobile Architect. He is also an OpenGroup Master Certified Specialist.

3 thoughts on “The Easiest way to check empty Objects in JavaScript

  1. Useful if available but you should, almost without exception, always use === to do comparisons in javascript, not ==.

Comments are closed.