How to check for an empty object in JavaScript

Last updated on Jun 3, 2021 by Suraj Sharma



In this tutorial, you will learn two ways to check if a JavaScript object is empty


1. Using JSON.stringify()


You can use the JSON.stringify method to convert an object to a JSON string and compare it with {} to check if the object is empty.


Example

const obj = {}

JSON.stringify(obj) === '{}' // true

const obj1 = {id: 1}

JSON.stringify(obj1) === '{}' // false



The best way to check if an object is empty is to use the Object.keys method.

The Object.keys method returns an array of the object's keys. If the length of the array is 0 then the object is empty else it is not.


Object.keys({}).length === 0; // true

Note: passing an empty array to the Object.keys method also returns an empty array as arrays are also objects.


const array = []

typeof array; // "object"

Object.keys(array).length === 0; // true

Therefore, you need an extra condition to verify whether the obj.constructor equals to Object or not.


Solution

const obj = {}

// Recommended solution
Object.keys(obj).length === 0 && obj.constructor === Object; // true

const array = []

Object.keys(array).length === 0 && array.constructor === Object; // false

array.constructor === Array; // true


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.