Languages
[Edit]
EN

JavaScript - how to check if object is empty?

7 points
Created by:
Kate_C
2892

Using JavaScript it is possible to check if object is empty in following way.

1. Custom function example

// ONLINE-RUNNER:browser;

function isEmpty(object) {
    for (var name in object) {
        if (object.hasOwnProperty(name)) {
            return false;
        }
    }
  
    return true;
}

// Usage example:

var object1 = { };

var object2 = {
    items: [ ]
};

var object3 = {
    result: false
};

var object4 = {
    ptint: function() { /* nothing here... */ }
};

console.log(isEmpty(object1)); // true
console.log(isEmpty(object2)); // false
console.log(isEmpty(object3)); // false
console.log(isEmpty(object4)); // false

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.