How to check if an object is empty?

You have a variable of type object in JavaScript. You want to check if it is empty. If the variable is null you can check it like

if(variableName == null )
    //do something.....

but this will not check if the object is empty.

Use this function to check if the object is empty.

function isObjectEmpty(object)
  var isEmpty = true;
  for(keys in object)
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  return isEmpty;

How to use the function

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;

// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 

// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;
This entry was posted in JavaScript, Web development and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>