Thursday, January 23, 2014

Check to see if a JavaScript object has any properties on it whatsoever.

In the name of doing this sort of thing you may want to sanity check if you even can! You cannot do a falsey check on an object "newed up" with ={} like so:

if (viewOpeners) {
   alert('has stuff');
} else {
   alert('holds nothing and is equal to just: {}');
}

 
 

The way to go is:

if (Object.keys(viewOpeners).length) {
   alert('has stuff');
} else {
   alert('holds nothing and is equal to just: {}');
}

 
 

...which allows for:

if (Object.keys(viewOpeners).length) {
   var topOfStack = Object.keys(viewOpeners)[Object.keys(viewOpeners).length - 1];
}

No comments:

Post a Comment