JavaScript isEmptyObject

JavaScript isEmptyObject: Three ways to check if an object is empty as I know:

1)

// jQuery implementation
function isEmptyObject(obj) {
    var name;
    for ( name in obj ) {
        return false;
    }
    return true;
}

2)

//Object.keys was only added in ECMAScript 5/JavaScript 1.8.5
function isEmptyObject(obj) {
    return Object.keys(obj).length === 0;
}

To add compatible Object.keys support in older environments that do not natively support it, copy the following snippet:

if (!Object.keys) {
  Object.keys = (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function (obj) {
      if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

      var result = [];

      for (var prop in obj) {
        if (hasOwnProperty.call(obj, prop)) result.push(prop);
      }

      if (hasDontEnumBug) {
        for (var i=0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
        }
      }
      return result;
    }
  })()
};

3)

// Only work in Firefox
function isEmptyObject(obj) {
    return obj.toSource() === "({})";
}

Yang Zhao

Read more posts by this author.


Comment