Skip to content

Instantly share code, notes, and snippets.

@apassiondev
Created December 3, 2020 22:34
Show Gist options
  • Save apassiondev/46818711a879f790159748325b490563 to your computer and use it in GitHub Desktop.
Save apassiondev/46818711a879f790159748325b490563 to your computer and use it in GitHub Desktop.
Check if a JavaScript object is empty
// 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