7 Easy Ways In JavaScript To Check If An Object Is Empty

How to check if an object is empty in JavaScript? Checking if an object is empty in JavaScript is a common task. You might encounter this when working with data structures, APIs, or JSON files. You might want to know if an object has any keys, properties, or values, or if it’s just a blank slate. By checking if an object is empty, you can avoid errors when trying to access an object that does not contain properties.

In this article, we will explore:

  • Different methods to check if an object is empty in JavaScript
  • ES6 methods to check if an object is empty
  • Check if an object is empty, undefined, or null.

Let’s dive deep.

JavaScript Object

Before going to check whether an object is empty, let’s see what an object is in JavaScript.In JavaScript, an object is just a collection of key-value pairs, like a dictionary. Each key or property is a string, and each value can be any JavaScript data type, including other objects.Objects are one of the non-primitive data types in JavaScript, and they are used extensively in JavaScript applications. Here is an example JavaScript object:
// JavaScript person object
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
    zipCode: "12345"
  }
};

In this example, person is an object that has four properties or keys. Those are firstName, lastName, age, and address. The address property itself is a nested object that has four properties street, city, state, and zipCode.

JavaScript Empty Object Check
JavaScript Check Is Empty Object In 7 Different Ways

How to check if object is empty?

We can determine if any object is empty or not by checking its keys or value length. There are different methods to check if an object is empty in JavaScript.

In this post, let’s look at four different methods that you can use to check if an object is empty.

1. Using Object.keys() method check is object empty

The JavaScript Object.keys() method returns an array of a given object’s property names. If the property name JavaScript array length of the object is equal to 0, we can confirm the object is empty.

Let’s see how to check if a JavaScript object is empty using Object.keys() with an example:

const emptyObject = {};

if (Object.keys(emptyObject).length === 0) {
  console.log("The object is empty");
}

// Output: "The object is empty"

In the above code, if the key length is 0 we can confirm the object is empty. Otherwise, we can do object manipulation if the object is not empty.

2. JavaScript check is empty object using for...in loop

A for...in loop iterates over the enumerable properties of an object and returns each property name. When compared to other approaches, this approach requires more lines of code to check if an object is empty. Use the for..in loop method as a last option to check if the object is empty.

Here is an example of a check object that is empty:

const emptyObject = {};

let isEmpty = true;
for (let key in emptyObject) {
  isEmpty = false;
  break;
}

if (isEmpty) {
  console.log("The object is empty");
}

// Output: "The object is empty"

3. Using Object.values() method to check if JavaScript object is empty

The Object.values() method returns an array of a given object’s property values. Check the JavaScript object length property to determine if the object is empty.

const emptyObject = {};
if (Object.values(emptyObject).length === 0) {
  console.log("The object is empty");
}

// Output: "The object is empty"
JavaScript Object Values
JavaScript Object Values

4. How to check empty object Using Object.entries() method

The JavaScript Object.entries() method returns an array of a given object’s key-value pairs. Check the JavaScript array length property to determine if the object is empty or not.

Check for empty objects using the Object.entries() method:

const emptyObject = {};
if (Object.entries(emptyObject).length === 0) {
  console.log("The object is empty");
}

// Output: "The object is empty"
JavaScript Object.entries()
JavaScript Object.entries()

ES6 check if object is empty

ES6 introduces three new methods to get the object’s properties. Let’s look at how to check if the object is empty in JavaScript. 

5. JavaScript ES6 empty object check using Object.getOwnPropertyNames() method

The Object.getOwnPropertyNames() method returns an array of all property or key names. This method returns non-enumerable properties for a given object.

Here is an example of how to check for empty objects in JavaScript:

const emptyObject = {};
if (Object.getOwnPropertyNames(emptyObject).length === 0) {
  console.log("The object is empty");
}

// Output: "The object is empty"
JavaScript Object.getOwnPropertyNames() Method
JavaScript Object.getOwnPropertyNames() Method

6. ES6 check object empty using Reflect.ownKeys() method

The Reflect.ownKeys() method returns an array of the given object’s property names and symbol keys.

Here is an example:

const emptyObject = {};
if (Reflect.ownKeys(emptyObject).length === 0) {
  console.log("The object is empty");
}

// Output: "The object is empty"

7. Using Object.getOwnPropertySymbols() method

The Object.getOwnPropertySymbols() method returns an array of the given object’s symbol keys.

Here is an example:

const emptyObject = {};

if (Object.getOwnPropertySymbols(emptyObject).length === 0) {
  console.log("The object is empty");
}

// Output: "The object is empty"

The best way to check if object is empty is by using a performance benchmark

I conducted a performance benchmark for all the methods listed above, using an empty object. The ES6 object empty check method performed better than the others, as it used the Object.getOwnPropertyNames() function to determine if the object had any properties. It allowed me to check 145,759 operations per second.

JavaScript check if object is empty performance
Performance Comparison of Different Empty Object Check Methods

Check if an object key value is empty

Let’s assume we have a person object with first name, last name, and age. Here is an example of how to check whether the last name is empty:

let person = {
  firstName: 'John',
  lastName: '',
  age: 30,
};

if (person && person.lastName.trim() === '')
  console.log('Last name is empty');
else {
  console.log('Last name is not empty');
}
// Output: "Last name is empty"

In the above example, the JavaScript trim() method is used to remove whitespace characters from the last name key.

Checking if an Object is empty, undefined, or null

There is a difference between an empty object, an undefined object, and an null object in JavaScript:
  • An empty object has no properties.
  • An undefined object is not defined.
  • A null object is an object that has no value.
Refer to the following code to check if an object is empty, undefined, or null:
const emptyObject = {};

if (!emptyObject) {
  console.log("The object is null or undefined.");
} else if (Object.keys(emptyObject).length === 0) {
  console.log("The object is empty.");
} else {
  console.log("The object is not empty.");
}

// Output: "The object is empty."

In the above code, we first check if the object is null or undefined using the logical not (!) operator. If it is null or undefined, we print a message to the console: "The object is null or undefined."

When the object is not null or undefined, we check if the object is empty using the Object.keys() method. If the object is empty, we print a message to the console, "The object is empty."

If the JavaScript object is not empty, we print a message to the console, "The object is not empty."

Frequently asked questions about check if object is empty

To check if an object is empty in JavaScript, you can use the Object.keys() method to get an array of the object’s keys and then check the array’s length. If the length is zero, the thing is empty.

function isObjectEmpty(obj) {
  return Object.keys(obj).length === 0;
}

The fastest way to check if an object is empty in JavaScript is by using the ES6 method Object.getOwnPropertyNames(), as it directly iterates over the object properties.

const emptyObject = {};
if (Object.getOwnPropertyNames(emptyObject).length === 0) {
  console.log("The object is empty");
}
If you are using Lodash in your project, you can use the isEmpty() function to check if an object is empty.
const _ = require('lodash');
const obj = { /* Your object here */ };
const isEmptyObject = _.isEmpty(obj);
In JavaScript, a Date object cannot be considered "empty". It will always have a value representing the current date and time, even if it hasn’t been explicitly set.

To check if an array of objects is empty, simply check the JavaScript array’s length.

const objectArray = [ /* Your array of objects here */ ];
const isArrayEmpty = (objectArray.length === 0);
If you want to check if an object is an array and also not empty, you can combine both checks as follows:
function isArrayNotEmpty(objectArray) {
   return Array.isArray(objectArray) && objectArray.length > 0;
}
To check if an object isn’t empty, you can use the same isObjectEmpty() function from the first answer and negate its result.
function isObjectNotEmpty(obj) {
   return Object.keys(obj).length > 0;
}
To check if an object is null, simply use the equality operator (===) to compare it with null.
function isObjectNull(obj) {
  return obj === null;
}

Conclusion

Checking if an object is empty, undefined, or null is essential in JavaScript programming. We have explored different methods in this article to determine if an object has any properties or not. This helps you avoid runtime errors when trying to access a property that does not exist in an object.

The methods we have covered include Object.keys(), for...in loop, Object.values(), Object.entries(), Object.getOwnPropertyNames(), Reflect.ownKeys(), and Object.getOwnPropertySymbols().

By using these methods, you can easily check if an object is empty in JavaScript and proactively prevent runtime errors.

Over to you: which method are you going to use to check if an object is empty?

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top