How To Check If An Object Is Empty In JavaScript

Check if an object is empty in JavaScript

There are some methods that can help you check if an object is empty in JavaScript. Let’s learn about it with the explanation and examples below.

Check if an object is empty in JavaScript

What is an object in JavaScript?

Take a student, for example. A student is an object with properties. A student has a name, birth, etc.

JavaScript objects have properties that define their characteristics. You can define a property by assigning it a value. 

Look at the example below.

const student = {
   name: "John",
   birth: 2002
};

Using the Object.keys() method

Syntax

Object.keys(myObject).length

Parameters

myObject: the name of the object you need to check if it is empty or not.

Return value

The size of the object.

Look at the example below.

const student = {};

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

Output

The object is empty

Using Object.getOwnPropertyNames() method

Syntax

Object.getOwnPropertyNames(myObject).length

Parameters

myObject: the name of the object you need to check if it is empty or not.

Return value

The size of the object.

Look at the example below.

const student = {name: "John", birth: 2002};

if (Object.getOwnPropertyNames(student).length == 0) {
    console.log("The object is empty");
} else {
    console.log("The object is not empty");
}

Output 

The object is not empty

Loop over object properties 

Look at the example below.

function isEmpty(myObj) {
    for (var item in myObj) {
        if (myObj.hasOwnProperty(item)) {
            return false;
        }
    }

    return true;
}

const student = {};

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

Output

The object is empty

Using JSON.stringify() method

The JSON.stringify() method converts a JavaScript value to a JSON string. If the object is empty, it will be converted to string like this: “{}”. So you can compare it with “{}” to check if an object is empty or not.

Look at the example below.

function isEmpty(myObj) {
    return JSON.stringify(myObj) === '{}'
}

const student = {name: "John", birth: 2002};

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

Output 

The object is not empty

Summary

Here are some solutions to resolve the question “How to check if an object is empty in JavaScript?”. Find the best way that works for you. We hope this tutorial is helpful to you. Thanks!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *