Here you will find the best ways to check whether a JavaScript object is empty or not.
5 Ways to check if an Object is Empty in JS
“Object.keys()” to Check whether a JS Object is Empty
The Object.keys()
is a static method that returns an array of a given object’s keys.
const user = {
name:"John",
age:24,
email:"[email protected]"
}
console.log(Object.keys(user));
// Result is -> [ 'name', 'age', 'email' ]
Now if the given object is empty, this (Object.keys()
) method will return an empty array, then by checking the length of the returned array we can say whether the object is empty or not.
const user = {
name:"John",
age:24,
email:"[email protected]"
}
if(Object.keys(user).length === 0){
console.log("The object is Empty.");
}
else{
console.log("The object is Not Empty.");
}
// Result is -> The object is Not Empty.
How to check variable is Array or Object in JavaScript?
“JSON.stringify()” method
JSON.stringify() method will convert an object to a JSON string. So if you pass an empty object into this method, it will only return empty curly braces {}
as string.
const user = {};
if (JSON.stringify(user) === "{}") {
console.log("Object is Empty");
} else {
console.log("Object is Not Empty");
}
// Result is -> Object is Empty
“for …in” Loop to Check if an Object is Empty
You can also use the JS for ...in
loop to check if an object is empty or not.
- for …in
- Wrap inside a function
const user = {
name: "John",
};
let isEmpty = true;
for (let prop in user) {
if (user.hasOwnProperty(prop)) {
isEmpty = false;
break;
}
}
if (isEmpty) {
console.log("Object is Empty.");
} else {
console.log("Object is Not Empty");
}
// Result is -> Object is Not Empty.
const user = {};
function isObjEmpty(obj) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
if (isObjEmpty(user)) {
console.log("Object is Empty.");
} else {
console.log("Object is Not Empty");
}
// Result is -> Object is Empty.
“_ Lodash” library’s isEmpty method
_.isEmpty()
method of the Lodash library can find out whether the given object is empty or not.
const _ = require("lodash");
const user = { name: "Jane" };
if (_.isEmpty(user)) {
console.log("Object is Empty.");
} else {
console.log("Object is Not Empty.");
}
// Result -> Object is Not Empty.
Check if an object is empty using “JQuery”
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" }); // false