by Sai gowtham

How to check if the object is empty using JavaScript

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

function isObjectEmpty(obj){
   return Object.getOwnPropertyNames(obj).length >= 1}

isObjectEmpty({ }) // false

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

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

Similarly, we can use the Object.keys() or Object.values() method.

Example:

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

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

Object.keys({id:1 }).length >=1 // true
  • The Object.keys() method returns an array with object keys.
  • The Object.values() method returns an array with object values.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 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)
284,472 students enrolled
40 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)
130,921 students enrolled
21 hours of video content
View Course