You can create a JavaScript object with an object literal({ }). The values in objects are written as name: value pairs (name and value separated by a colon).
JavaScript check if object is empty
To check if the Object is empty in JavaScript, use the Object.keys() method with an additional constructor. The Object.keys() is a built-in JavaScript function that returns an array of a given object’s own enumerable property names.
const objct = {};
if (Object.keys(objct).length === 0 && objct.constructor === Object) {
console.log("The Object is empty")
}
else {
console.log("The Object is not empty")
}
Output
The Object is empty
Let’s add something to the object and see the output.
const objct = { name: "Pegasus" };
if (Object.keys(objct).length === 0 && objct.constructor === Object) {
console.log("The Object is empty")
}
else {
console.log("The Object is not empty")
}
Output
The Object is not empty
That’s it. We have successfully checked if the Object is empty or not.
For ES3 and older, there’s no easy way to do this. You’ll have to loop over the properties explicitly.
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false
}
return true
}
const objct = {}
if (isEmpty(objct)) {
console.log("The Object is empty")
}
else {
console.log("The object is not empty")
}
Output
The Object is empty
The object is empty, so it returns true. Otherwise, it returns false.
That’s it for this tutorial.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. Krunal has experience with various programming languages and technologies, including PHP, Python, and expert in JavaScript. He is comfortable working in front-end and back-end development.