Javascript check if object is empty

Posted on February 5, 2019 by Suresh Kamrushi in Javascript

This is very frequently facing issue, checking a javascript object is empty or not. You can do that using plain Javascript or jQuery.
Here is example how you do it using javascript:

1) var sampleObj = {one:"1"};
   Object.keys(sampleObj).length) //return 1
2) var sampleObj = {};
   Object.keys(sampleObj).length) //return 0

Jquery also provide isEmptyObject() function to check whether object empty or not. you can use it as below:

1) var sampleObj = {one:"1"};
   jQuery.isEmptyObject(sampleObj) //return false

2) var sampleObj = {};
   jQuery.isEmptyObject(sampleObj) //return true

Hope this help someone!!!

Tagged as