- # How to Check if Object is Empty in JavaScript
- # What is Vanilla JavaScript
- # A. Empty Object Check in Newer Browsers
- # Why do we need an additional constructor check?
- # Solving false positive with constructor check
- # Testing empty check on other values
- # Improve empty check for null and undefined
- # B. Empty Object Check in Older Browsers
- # Checking empty object with JavaScript
- # Checking empty object with external libraries
- # Vanilla vs Libraries
- # Conscious Decision Making
- # Community Input
- How to Check if an Object is Empty in JavaScript – JS Java isEmpty Equivalent
- How to Check if an Object is Empty with Object.keys()
- How to Check if an Object is Empty with a for…in Loop
- How to Check if an Object is Empty with JSON.stringify()
- How to Check if an Object is Empty with Lodash
- That’s It! 💪
# How to Check if Object is Empty in JavaScript
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 JavaScript, we have 9 built-in constructors.
new Object(); new String(); new Number(); new Boolean(); new Array(); new RegExp(); new Function(); new Date();
So we can create an empty object with new Object() . Side note: you should NEVER create an object using the constructor. It’s considered bad practice, see Airbnb Style Guide
const obj = new Object(); Object.keys(obj).length === 0; // true
So just using the Object.keys , it does return true when the object is empty ✅. But what happens when we create a new object instance using these other constructors.
function badEmptyCheck(value) return Object.keys(value).length === 0; > badEmptyCheck(new String()); // true 😱 badEmptyCheck(new Number()); // true 😱 badEmptyCheck(new Boolean()); // true 😱 badEmptyCheck(new Array()); // true 😱 badEmptyCheck(new RegExp()); // true 😱 badEmptyCheck(new Function()); // true 😱 badEmptyCheck(new Date()); // true 😱
Ah ya ya, we have a false positive 😱
# Solving false positive with constructor check
Let’s correct this by adding a constructor check.
function goodEmptyCheck(value) Object.keys(value).length === 0 && value.constructor === Object; // 👈 constructor check > goodEmptyCheck(new String()); // false ✅ goodEmptyCheck(new Number()); // false ✅ goodEmptyCheck(new Boolean()); // false ✅ goodEmptyCheck(new Array()); // false ✅ goodEmptyCheck(new RegExp()); // false ✅ goodEmptyCheck(new Function()); // false ✅ goodEmptyCheck(new Date()); // false ✅
Beautiful! We have covered our edge case 👍
# Testing empty check on other values
Alright, let’s test our method on some values and see what we get 🧪
function isEmptyObject(value) return Object.keys(value).length === 0 && value.constructor === Object; >
Looks good so far, it returns false for non-objects.
isEmptyObject(100) // false isEmptyObject(true) // false isEmptyObject([]) // false
🚨But watch out! These values will throw an error.
// TypeError: Cannot covert undefined or null ot object goodEmptyCheck(undefined); goodEmptyCheck(null);
# Improve empty check for null and undefined
If you don’t want it to throw a TypeError , you can add an extra check:
let value; value // 👈 null and undefined check && Object.keys(value).length === 0 && value.constructor === Object; value = null; // null value = undefined; // undefined
Perfect, no error is thrown 😁
# B. Empty Object Check in Older Browsers
What if you need to support older browsers? Heck, who am I kidding! We all know when I say older browsers, I’m referring to Internet Explorer 😂 Well, we have 2 options. We can stick with vanilla or utilize a library.
# Checking empty object with JavaScript
The plain vanilla way is not as concise. But it does do the job 👍
function isObjectEmpty(value) return ( Object.prototype.toString.call(value) === '[object Object]' && JSON.stringify(value) === '<>' ); >
It returns true for objects.
isObjectEmpty(>); // true ✅ isObjectEmpty(new Object()); // true ✅
Excellent, it doesn’t get trick by our constructor objects 😉
isObjectEmpty(new String()); // false ✅ isObjectEmpty(new Number()); // false ✅ isObjectEmpty(new Boolean()); // false ✅ isObjectEmpty(new Array()); // false ✅ isObjectEmpty(new RegExp()); // false ✅ isObjectEmpty(new Function()); // false ✅ isObjectEmpty(new Date()); // false ✅
And we’re covered for null and undefined . It will return false and not throw a TypeError .
isObjectEmpty(null); // false isObjectEmpty(undefined); // false
# Checking empty object with external libraries
There are tons of external libraries you can use to check for empty objects. And most of them have great support for older browsers 👍
jQuery.isEmptyObject(>); // true
# Vanilla vs Libraries
The answer is it depends! I’m a huge fan of going vanilla whenever possible as I don’t like the overhead of an external library. Plus for smaller apps, I’m too lazy to set up the external library 😂. But if your app already has an external library installed, then go ahead and use it. You will know your app better than anyone else. So choose what works best for your situation 👍
# Conscious Decision Making
I love this mindset so much! Often, we have to make some compromises. And there’s nothing wrong with that. Especially, when you work within a team, sometimes disagreement arises. But in the end, we have to make a decision. This doesn’t mean we blind ourselves from other options. Quite the opposite, we do our best to seek other possible solutions and understand each implication. That’s how we can make an informed decision. Maybe compromise is not the right word, I think of it as «conscious decision making» 😆
Yup, I too can coin terms, just like Gwyneth Paltrow’s conscious uncoupling
. Maybe I should start a tech version of Goop. but minus the jade roller and the other «interesting» products 😂
# Community Input
for (var key in object) if (object.hasOwnProperty(key)) return false; > > return true;
Object.prototype.toString.call(a) == '[object Object]' && JSON.stringify(a) == '<>';
How to Check if an Object is Empty in JavaScript – JS Java isEmpty Equivalent
Joel Olawanle
An object is one of the most commonly used data types in programming. An object is a collection of related data stored as key-value pairs. For example:
When working with objects, you may need to check if an object is empty before performing a function.
In JavaScript, there are various ways you can check if an object is empty. In this article, you will learn the various ways you can do this, the options that can be attached, and why.
Note: An object is considered empty when it has no key-value pair.
In case you are in a rush, here is a basic example:
const myEmptyObj = <>; // Works best with new browsers Object.keys(myEmptyObj).length === 0 && myEmptyObj.constructor === Object // Works with all browsers _.isEmpty(myEmptyObj)
Both methods will return true . Let’s now understand these and more options you can use to check if an object is empty in JavaScript.
How to Check if an Object is Empty with Object.keys()
The Object.keys() method is a static object method introduced in ECMAScript6 (ES6) and is supported in all modern browsers. This method returns an array with the keys of an object. For example:
let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; console.log(Object.keys(userDetails)); // ["name","username","age"]
With this, you can now apply the .length property. If it returns zero (0), the object is empty.
let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; console.log(Object.keys(userDetails).length); // 3 console.log(Object.keys(myEmptyObj).length); // 0
You can now use this method to check if an object is empty with an if statement or create a function that checks.
const isObjectEmpty = (objectName) =>
This will return either true or false . If the object is empty, it will return true , otherwise, it will return false .
let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return Object.keys(objectName).length === 0 >console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true
Note: Checking the length alone is not the best option when checking if an object is empty or for any datatype. It is always best to confirm if the data type is correct.
To do this, you can use the constructor check:
const isObjectEmpty = (objectName) =>
This way, you are liable to get a more thorough check.
Thus far, everything has worked fine. But you might also want to avoid throwing a TypeError when a variable is undefined or a value of null is passed instead of <> . To fix this, you can add an extra check:
const isObjectEmpty = (objectName) => < return ( objectName && Object.keys(objectName).length === 0 && objectName.constructor === Object ); >;
In the code above, an extra check is added. This means that it will return either null or undefined if it is not an empty object, as shown in the example below:
let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; let nullObj = null; let undefinedObj; const isObjectEmpty = (objectName) => < return ( objectName && Object.keys(objectName).length === 0 && objectName.constructor === Object ); >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true console.log(isObjectEmpty(undefinedObj)); // undefined console.log(isObjectEmpty(nullObj)); // null
Note: This applies to other object static methods, meaning you can make use of Object.entries() or Object.values() instead of Object.keys() .
How to Check if an Object is Empty with a for…in Loop
Another method you can use is the ES6 for…in loop. You can use this loop alongside the hasOwnProperty() method.
const isObjectEmpty = (objectName) => < for (let prop in objectName) < if (objectName.hasOwnProperty(prop)) < return false; >> return true; >;
The method above will loop through each object property. If it finds a single iteration, the object is not empty. Also, the hasOwnProperty() will return a boolean indicating whether the object has the specified property as its property.
let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < for (let prop in objectName) < if (objectName.hasOwnProperty(prop)) < return false; >> return true; >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true
How to Check if an Object is Empty with JSON.stringify()
You can also make use of the JSON.stingify() method, which is used to convert a JavaScript value to a JSON string. This means it will convert your object values to a sting of the object. For example:
let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; console.log(JSON.stringify(userDetails)); Output: ""
This means when it is an empty object, then it will return «<>» . You can make use of this to check for an empty object.
const isObjectEmpty = (objectName) => < return JSON.stringify(objectName) === "<>"; >;
This will return true if the object is empty, otherwise false :
let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return JSON.stringify(objectName) === "<>"; >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true
How to Check if an Object is Empty with Lodash
Finally, some of the methods I’ve explained here might work for older browser versions, while others may not work. If you are concerned about a solution that will work for both old and modern browser versions, you can use Lodash.
Lodash is a modern JavaScript utility library that can perform many JavaScript functionalities with very basic syntax.
For example, if you want to check if an object is empty, you only need to use the «isEmpty» method.
Installing Lodash into your project is quite easy. All you have to do is make use of this command:
You can now initialize the underscore method and make use of this method.
const _ = require('lodash'); let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return _.isEmpty(objectName); >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true
That’s It! 💪
I’ve enjoyed exploring the various ways you can check if an object is empty. Feel free to use the best method that fits your project or task.
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.