Sitemap

How to Check if Object is Empty in JavaScript

5 min readJul 15, 2020
Press enter or click to view image in full size
Code snippet of How to Check if Object is Empty in JavaScript for newer browser and older browse

Here’s a Code Recipe to check if an object is empty or not. For newer browsers, you can use plain vanilla JS and use the new “Object.keys” 🍦 But for older browser support, you can install the Lodash library and use their “isEmpty” method 🤖

const empty = {};/* -------------------------
Plain JS for Newer Browser
----------------------------*/
Object.keys(empty).length === 0 && empty.constructor === Object
// true
/* -------------------------
Lodash for Older Browser
----------------------------*/
_.isEmpty(empty)
// true

What is Vanilla JavaScript

Vanilla JavaScript is not a new framework or library. It’s just regular, plain JavaScript without the use of a library like Lodash or jQuery.

A. Empty Object Check in Newer Browsers

We can use the built-in Object.keys method to check for an empty object.

const empty = {};Object.keys(empty).length === 0 && empty.constructor === Object;

Why do we need an additional constructor check?

You may be wondering why do we need the constructor check. Well, it's to cover for the wrapper instances. In…

--

--

Samantha Ming
Samantha Ming

Written by Samantha Ming

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛

Responses (6)