Created
December 3, 2020 22:34
-
-
Save apassiondev/46818711a879f790159748325b490563 to your computer and use it in GitHub Desktop.
Check if a JavaScript object is empty
This file contains 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
// Check if an object is empty | |
// Option #1 | |
const checkOpt1 = (obj) => { | |
for(let prop in obj) { | |
if (obj.hasOwnProperty(prop)) | |
return false | |
} | |
return true | |
} | |
// Option #2: perform check inclduing `null` & `undefined` object | |
const checkOpt2 = (obj) => (obj && Object.keys(obj).length === 0 && obj.constructor === Object) | |
// Option #3: for older browsers | |
const checkOpt3 = (obj) => Object.prototype.toString.call(obj) = '[object Object]' && JSON.stringify(obj) === '{}' | |
// References | |
// https://www.samanthaming.com/tidbits/94-how-to-check-if-object-is-empty/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment