Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How To Check If Javascript Object Is Empty
#1
With JavaScript, it can be difficult to check whether an object is empty.

With Arrays, you can easily check with
myArray.length , but on the other hand, objects do not work that way.
The best way to check if an object is empty is by using a utility function like the one below.


Code:
function isEmpty (obj ) {
for(var key in obj ) {
if(obj .hasOwnProperty (key ))
return false;
}
return true;
}


So if you have an empty object, you can check whether it is empty by using the above function.


Code:
var myObj = {}; // Empty Object
if(isEmpty (myObj )) {
// Object is empty (Would return true in this example)
} else {
// Object is NOT empty
}


Alternatively, you can write the isEmpty function on the Object prototype.


Code:
Object.prototype .isEmpty = function() {
for(var key in this ) {
if(this .hasOwnProperty (key ))
return false;
}
return true;
}


Then you can easily check if the object is empty like so.


Code:
var myObj = {
myKey: "Some Value"
}
if(myObj .isEmpty ()) {
// Object is empty
} else {
// Object is NOT empty (would return false in this example)
}

Extending the object prototype is not the best thing to do as it can cause some browser issues and other issues with certain frameworks (it's also not always reliable in certain environments). The example I gave is pretty much framework agnostic although.

This is one of those utility functions that will always be useful, especially if you deal with a lot of objects on a daily basis (like I do).
It takes so long to learn simplicity.
Facebook Share


Possibly Related Threads...
Thread
  HELP: How Can I Create A Javascript Ads Rotator For My Site
  Beginner Javascript Coding Mistakes To Avoid
  Concatenate Many Arrays Uniquely With Javascript
  Javascript Time Ago Function
  Shortest Code For Random Number Between 1 And N In Javascript
  Javascript Text Editor Right In Your Browser In One Line Of Code
  Getting Current Location With Javascript
  How To Create An Image Slider With Javascript
  Convert Numbers To Roman Numerals With Javascript
  TUTORIAL: How To Make A Digtal Clock With Javascript




Users browsing this thread: 1 Guest(s)