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 JavaScript 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 JavaScript 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.