Created
December 8, 2020 04:42
-
-
Save junaidtk/dfaca2b9902bbbb7f96c0f8648561b53 to your computer and use it in GitHub Desktop.
Empty Javascript Object check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
To check a javascript object is empty, then you can use below code. | |
In Newer browser empty checking: | |
================================ | |
const empty = {}; | |
Object.keys(empty).length === 0 && empty.constructor === Object; | |
First method: | |
function badEmptyCheck(value) { | |
return Object.keys(value).length === 0; | |
} | |
This method will return true when object is empty. | |
Second method: | |
function goodEmptyCheck(value) { | |
Object.keys(value).length === 0 | |
&& value.constructor === Object; // 👈 constructor check | |
} | |
This will return false for empty object but it will trigger an type error for Null and undefined object. | |
The best attempt for checking an object is empty is given below. | |
function isEmptyObject(value) { | |
return Object.keys(value).length === 0 && value.constructor === Object; | |
} | |
In older browser, you can use below method to check empty object: | |
================================================================= | |
function isObjectEmpty(value){ | |
return Object.prototype.toString.call(value) === "[object Object]" && JSON.stringify(value) === "{}"; | |
} | |
Checking an object is empty by using the Jquery: | |
================================================ | |
jQuery.isEmptyObject({}); | |
// true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment