How to check if JavaScript Object is empty or not/How to check if Javascript Array object is empty or not

While working with Javascript sometimes you have to check if a Javascript object/array is empty or it contains some keys/objects.

To check if Javascrippt Array is empty or not, Someone can use below code(JsFiddle):


var myArray = [];

console.log("If Array is empty", myArray.length); // Output would be "0"

myArray.push("1");

myArray.push("2");

console.log("If Array is empty", myArray.length); // Output would be "2"

To check if Javascrippt Object is empty or not, Someone can use below function code(JSFiddle):


function isObjectEmpty(Obj) {
for(var key in Obj) {
if(Obj.hasOwnProperty(key))
return false;
}
return true;
}

var myObj = {}; // Empty Object

console.log("myObj", isObjectEmpty(myObj)); // returns "true"

var myObj = {"name": "youvcode"}; // Empty Object

console.log("myObj", isObjectEmpty(myObj)); // returns "false"

 

 

Please let us know in comments if you have any better solution to check this. Thank you for reading this article.

 

Leave a Reply