In this article we will learn how to check if an object is empty in JavaScript.
It is very common to check if an object is empty in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to check if an object is empty or not.
Now let's imagine that we have an object like this:
const myObject = {
name: "John",
age: 30,
country: "USA"
}
And we want to check if this object is empty or not.
How to solve this problem?
The solution to this problem is easy, but unfortunately there is no built-in function that calculates the number of elements in the object such as an array, so we must convert the object into an array and then use length
property.
Solution:
As we said before, we can convert our object to an array and then use length
property to get the length of elements.
Let's see an example
// Object
const myObject = {
name: "John",
age: 30,
country: "USA"
}
// Convert to an array
const toArr = Object.entries(myObject);
// Length of elements:
console.log(toArr.length);
Output
3
Create a function
Now we already know the length of the object, and now we will create a function that returns true
or false
, that function knows if the object is empty or not.
// Create a function
function isEmpty(obj) {
// Convert to an array
const toArr = Object.entries(obj);
// If object is empty
if (toArr.length === 0) {
return true;
}
// Otherwise
return false;
}
// Object
const object1 = {
name: "John",
age: 30,
country: "USA"
}
// Object
const object2 = {};
// Tests
console.log(isEmpty(object1));
console.log(isEmpty(object2));
Output
false
true
Thank you for reading
Thank you for reading my blog. 🚀