How to check if Object is Empty or not?
I’ll show you how to check if an object is empty in JavaScript. Checking if an object is empty is not as simple as checking if an array is empty.
Let’s take the following empty sample object named person, below:
const person = {}
A plain and simple JavaScript object, initialized without any keys or values. Empty.
There are multiple ways to check if the person object is empty, in JavaScript, depending on which version you are using.
ES6 is the most common version of JavaScript today, so let’s start there. ES6 provides us with the handy Object.keys function:
Object.keys(person).length
Example:
--------
const person = {}
if (Object.keys(person).length === 0) {
// is empty
} else {
// is not empty
}
If you are using ES7 (the newer version of ECMAScript), you can use the following function:
const person = {}
if (Object.entries(person).length === 0) {
// is empty
} else {
// is not empty
}