How to check an object is empty or not in Javascript?

There are four easy ways to check an object is empty or not in Javascript.

1. With vanilla Javascript:

function isEmpty(obj) {
  for(let prop in obj) {
    if(obj.hasOwnProperty(prop)) {
      return false;
    }
  }
  return JSON.stringify(obj) === JSON.stringify({});
}

console.log(isEmpty({})) // true 
console.log(isEmpty({ name: '4codev' })) // false 


2. With Lodash:

import _ from 'lodash';

_.isEmpty({}); // true
_.isEmpty({ name: '4codev' }); // false


3. Use Underscore (The same as with Lodash library)

import _ from 'underscore';

_.isEmpty({}); // true
_.isEmpty({ name: '4codev' }); // false


4. Use jQuery:

import $ from 'jquery';

$.isEmptyObject({}); // true
$.isEmptyObject({ name: '4codev' }); // false


© 2019 4codev

Created with love by Sil.