Skip to content

Instantly share code, notes, and snippets.

@Alonso-Pablo
Created December 5, 2021 16:14
Show Gist options
  • Save Alonso-Pablo/8f8b443c8be50e73c4e96d7843c30a97 to your computer and use it in GitHub Desktop.
Save Alonso-Pablo/8f8b443c8be50e73c4e96d7843c30a97 to your computer and use it in GitHub Desktop.
Check if the object is empty or not
// Objects:
const emptyObj = {}
const noEmptyObj = { foo: 'bar'}
// Option 1:
function isObjEmpty(obj) {
return (Object.keys(obj).length)
? 'No empty'
: 'Empty'
}
// Results:
isObjEmpty(emptyObj) // 'Empty'
isObjEmpty(noEmptyObj) // 'No empty'
// Option 2:
function isObjectEmpty(obj) {
return (Object.entries(obj).length)
? 'No empty'
: 'Empty'
}
// Results:
isObjectEmpty(emptyObj) // 'Empty'
isObjectEmpty(noEmptyObj) // 'No empty'
// How does it work:
// Object.keys():
Object.keys(emptyObj) // []
Object.keys(emptyObj).length // 0
Object.keys(noEmptyObj) // [ 'foo' ]
Object.keys(noEmptyObj).length // 1
// Object.entries():
Object.entries(emptyObj) // []
Object.entries(emptyObj).length // 0
Object.entries(noEmptyObj) // [ [ 'foo', 'bar' ] ]
Object.entries(noEmptyObj).length // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment