How to Check if an Object is Empty in JavaScript
Table of Contents
Objects in JavaScript are a collection of key-value pairs.
Sometimes it can be useful to know if an object is empty or not. For example, you might want to check if an object is empty before you try to access a property on it.
In this post, we'll learn how to check if an object is empty in JavaScript.
How to check if an object is empty in JavaScript
There are a few ways to check if an object is empty in JavaScript.
First, let's start with an example empty object:
JAVASCRIPTconst object = {};
The best way to check an object is empty is to use the Object.entries()
method.
This method returns an array of a given object's own enumerable key-value pairs.
If the object is empty, the array will be empty.
JAVASCRIPTconst object = {};
if (Object.entries(object).length === 0) {
console.log("Object is empty");
} else {
console.log("Object is not empty");
}
BASHObject is empty
Alternatively, we can turn this into a method:
JAVASCRIPTconst object = {};
const isEmpty = (obj) => Object.entries(obj).length === 0;
if (isEmpty(object)) {
console.log("Object is empty");
} else {
console.log("Object is not empty");
}
BASHObject is empty
Just make sure the variable that you are using is an object.
If you want to check, you can compare the constructor:
JAVASCRIPTconst object = {};
const isObject = (obj) => obj.constructor === Object;
if (isObject(object)) {
console.log("Object is an object");
} else {
console.log("Object is not an object");
}
Conclusion
In this post, we learned how to check if an object is empty in JavaScript.
Simply use the Object.entries()
method to check if an object is empty by checking how many key-value pairs it has.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Setting Up Stylus CSS Preprocessor
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js