This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Johnny Simpson
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!
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Johnny Simpson
Johnny Simpson | Sciencx (2023-02-04T23:07:09+00:00) How to Check if Object is Empty in JavaScript. Retrieved from https://www.scien.cx/2023/02/04/how-to-check-if-object-is-empty-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.