Defining a new object in Javascript is pretty easy - but what if you want to find out if it's empty? For example, {}
is an empty object, but how do we actually test that this is the case?
let myObject = {}
The easiest (and best) way to do this, is to use Object.keys()
.
This method turns all the keys in an object to an array, which we can then test the length of:
let myObject = {}
console.log(Object.keys(myObject).length) // Returns 0!
But wait... Javascript is well known for how it handles types strangely - and new constructors return an object with length 0:
let myFunction = function() {
console.log("hello")
}
console.log(Object.keys(new myFunction()).length)
Fortunately, we can check if something is an object by checking its constructor
property:
console.log(function myFunction() {}.constructor) // Function
console.log({}.constructor) // Object
Therefore, we can check if an object is empty if its constructor is an Object
, and it has an Object.keys()
value of 0
:
let empty = {}
let isObjEmpty = (obj) => {
return Object.keys(obj).length === 0 && obj.constructor === Object
}
console.log(isObjEmpty(empty)); // Returns true, Object is empty!