by Sai gowtham

How to check if the object is empty using JavaScript

In javascript, we can use Object.getOwnPropertyNames method to check if the given object is empty or not.

First way

function isObjectEmpty(obj){

   return Object.getOwnPropertyNames(obj).length >= 1

}

isObjectEmpty({ }) // false

isObjectEmpty({id:1,name:"js"}) // true

If we pass an empty object to the Object.getOwnPropertyNames it returns the empty array.so that by using the length of that array we can check easily is the given object empty or not.

Second way

We can also use Object.keys() or Object.values()

Object.values({ }).length >= 1  // false


Object.values({ id:1}).length >= 1  // true


Object.keys({id:1 }).length >=1 // true

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course