How to Check if an Object is Empty in Javascript

In this tutorial, you will learn how to check if an object is empty in javascript. In an object, you can dynamically add or remove properties.  Sometimes it becomes hard to keep track of the existence of those properties in an object.  As a result, you might end up trying to access a property in an empty object.

It is extremely important to verify if the object is empty or not before even accessing any of its properties.  This will help you in reducing the number of unforeseen bugs in production.

To solve the above problem, we will make use of the Object class. It has the keys() method that returns an array of all keys in an object.  Arrays have built-in length property which returns the total number of items in an array.  If the length is 0, that means the array is empty.

In the following example, we have an empty object and we will use Object class to verify if the object is empty or not.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Check” and for the h1 element is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Check</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button{
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected 2 elements button and h1 using the document.querySelector() method and stored them in btnCheck and result variables respectively.
  • We have a global variable user and it holds an empty object as its value.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are making use of the keys() method of the Object class to get all keys in the userobject. This method returns an array so we are using the length property to get its length.
  • If length is equal to 0, that means the object is empty.  Depending upon the result of verification, we are displaying the Boolean value in the h1 element. In our case, the user object is empty so we will get True as a result.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let user = {};

btnCheck.addEventListener('click', () => {
    result.innerText = Object.keys(user).length == 0 ? 'True' : 'False';
});