Check if Object is Empty in JavaScript without lodash

Lodash is always the favorite library for developers to perform small operation without writing any extra code. So you may have used this isEmpty function of the lodash to check for an empty object. In this tip article we will gonna learn how to do that without lodash.


// Instead of this

const obj = {};

// true

You can use something like this

const obj = {};

Object.keys(empty).length === 0 && empty.constructor === Object;
// true

You maybe wondering why we need to add extra constructor check.

In JS we have 9 constructor and our logic will not be good for all types of constructors.

function emptyCheck(value) {
  return Object.keys(value).length === 0;

emptyCheck(new String());    // true 
emptyCheck(new Number());    // true 

You can see our output is not correct. Just to handle this case we are adding a constructor check.

To handle null and undefined case we can add one more check.

value && Object.keys(value).length === 0 && value.constructor === Object;

How to check an element is in viewport using Intersection Observer API

1 Comment

Tip 2: Create an array of n size without lodash - Blog React · July 28, 2020 at 3:15 am

[…] Tip 1: Check if Object is Empty in JavaScript without lodash […]

Comments are closed.