Skip to content

Instantly share code, notes, and snippets.

@MaraScott
Last active December 13, 2015 18:49
Show Gist options
  • Save MaraScott/4957956 to your computer and use it in GitHub Desktop.
Save MaraScott/4957956 to your computer and use it in GitHub Desktop.
Name : is_empty(obj) - Language : JavaScript - type : function - platform : generic
function is_empty(obj) {
"use strict";
// assign object type
var objType = Object.prototype.toString.call(obj);
// is type === object
if (objType === '[object Object]') {
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length && obj.length > 0) { return false; }
if (obj.length && obj.length === 0) {return true; }
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) { return false; }
}
// is type === array OR type === string
} else if ( objType === '[object Array]' || objType === '[object String]' ) {
if (obj.length && obj.length > 0) { return false; }
}
return true;
}
// Examples
console.log(
is_empty(""), // True
is_empty([]), // True
is_empty({}), // True
is_empty({length: 0, custom_property: []}), // True
is_empty("Hello"), // False
is_empty([1,2,3]), // False
is_empty({test: 1}), // False
is_empty({length: 3, custom_property: [1,2,3]}) // False
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment