JavaScript is Object Empty
by Slava Fomin II
JavaScript
/**
* Returns true if specified object has no properties,
* false otherwise.
*
* @param {object} object
* @returns {boolean}
*/
function isObjectEmpty(object)
{
if ('object' !== typeof object) {
throw new Error('Object must be specified.');
}
if (null === object) {
return true;
}
if ('undefined' !== Object.keys) {
// Using ECMAScript 5 feature.
return (0 === Object.keys(object).length);
} else {
// Using legacy compatibility mode.
for (var key in object) {
if (object.hasOwnProperty(key)) {
return false;
}
}
return true;
}
}
// Simple test.
var errorsCount =
!isObjectEmpty({
foo: 'foo'
}) ? 0 : 1
+
!isObjectEmpty({
foo: 'foo',
bar: 'bar'
}) ? 0 : 1
+
!isObjectEmpty({
func: function() {}
}) ? 0 : 1
+
isObjectEmpty({}) ? 0 : 1
+
isObjectEmpty(new Object()) ? 0 : 1
+
isObjectEmpty(null) ? 0 : 1
;
alert(errorsCount == 0 ? 'Test OK!' : 'Test failed!');