Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active February 19, 2021 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-doherty/d8b8a19c48745a6e4986b2b6222fe472 to your computer and use it in GitHub Desktop.
Save john-doherty/d8b8a19c48745a6e4986b2b6222fe472 to your computer and use it in GitHub Desktop.
Check if a variable is really empty in JavaScript
/**
* Checks if a JavaScript value is empty
* @example
* isEmpty(null); // true
* isEmpty(undefined); // true
* isEmpty(''); // true
* isEmpty([]); // true
* isEmpty({}); // true
* @param {any} value - item to test
* @returns {boolean} true if empty, otherwise false
*/
function isEmpty(value) {
return (
value === null || // check for null
value === undefined || // check for undefined
value === '' || // check for empty string
(Array.isArray(value) && value.length === 0) || // check for empty array
(typeof value === 'object' && Object.keys(value).length === 0) // check for empty object
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment