Last active
February 19, 2021 10:51
-
-
Save john-doherty/d8b8a19c48745a6e4986b2b6222fe472 to your computer and use it in GitHub Desktop.
Check if a variable is really empty in JavaScript
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
/** | |
* 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