javascript – How to check that the {} object is not empty?

Question:

How to properly check in JavaScript if an object is empty or contains some properties?

Answer:

For example like this:

if (Object.keys(obj).length == 0) {
    console.log('пуст');
}

But Object.keys() , Object.keys() is not available everywhere (you need to check the Show obsolete browsers? Box in order to see all browsers), so you can use a polyfill , or such, for example, a function:

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

Or, with jQuery, if you haven't changed the Object prototype:

if ($.isEmptyObject({});) {
     console.log('пуст');
}
Scroll to Top