How to check if a JavaScript Object is Empty

This video covers a common question JavaScript developers come across. How do I test for an empty JavaScript object?


const users = {}
if(users && Object.entries(users).length === 0){
console.log('Object is empty');
else console.log('Object is either null or undefined')

Full Transcript

0:00 Hi there. Welcome to today's video and I'm Deeksha Sharma from bonsaiilabs. Today's video is a common operation on objects in JavaScript. How to check if an object is empty? Let's write some code to see how you can do that. Let's say we have an object users with empty curly braces. Our goal is to check if users contain any key value pairs or to say entries inside it. To check for empty objects, JavaScript provides a method on objects called entries. It returns an array of entries an object contains. We can use it by calling object.entries and pass it as an argument users whose key value pairs are to be returned. And since it returns an array, we can check if the length of the array is zero, it means that object doesn't contain anything. We can now log a message - users is empty, if the condition is true. We can omit the curly brackets

1:02 since there is only one line we want to display on console. We run it and there you go. It meets the condition, but we might run into problems if we don't check one thing. Let's try to change the value of users from empty to null. And now let's try to run it and you will see this error. That is because we never checked if the users is a valid object. What if the user's object is either null or undefined? So always check whether the object is null or undefined before checking if it's empty. Otherwise it may result in runtime errors. Now when we run it next time, it doesn't give any output. That's because users is already null and the message is going to be displayed. If users is a valid object and the number of entries inside the object are zero. Since that is not the case, it didn't displayed any message. Let's try to change it back to an empty object and run it again and it logged the message - users is empty. This is one of the most common operations you might be performing in your work, and that's all I wanted to cover. If you liked this video, be sure to subscribe. And until then my friends keep learning and share your knowledge.