Last active
November 1, 2024 07:48
-
-
Save skoshy/69a7951b3070c2e2496d8257e16d7981 to your computer and use it in GitHub Desktop.
Determines if any value is "falsy" 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
// this function takes in any parameter and can tell if it's "falsy" or not. | |
// falsy means it's either false, 0, null, undefined, NaN, or an empty string/array/object | |
// see the test cases at the bottom for a clearer picture | |
function isFalsy(item) { | |
try { | |
if ( | |
!item // handles most, like false, 0, null, etc | |
|| ( | |
typeof item == "object" && ( | |
Object.keys(item).length == 0 // for empty objects, like {}, [] | |
&& !(typeof item.addEventListener == "function") // omit webpage elements | |
) | |
) | |
) { | |
return true; | |
} | |
} catch(err) { return true; } | |
return false; | |
}; | |
/******************* | |
**** TEST CASES **** | |
********************/ | |
// These are falsy. isFalsy(value) === true | |
console.log(isFalsy(null)); | |
console.log(isFalsy(undefined)); | |
console.log(isFalsy(NaN)); | |
console.log(isFalsy(0)); | |
console.log(isFalsy(false)); | |
console.log(isFalsy('')); | |
console.log(isFalsy([])); | |
console.log(isFalsy({})); | |
console.log("----"); | |
// These are not falsy. isFalsy(value) === false | |
console.log(isFalsy("0")); | |
console.log(isFalsy(document.createElement('div'))); | |
console.log(isFalsy(window)); | |
console.log(isFalsy(console)); | |
console.log(isFalsy(document)); | |
console.log(isFalsy({0: 3, 'test': 'hi'})); | |
console.log(isFalsy([1,2,3])); |
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
function isTruthy(item) { | |
return !isFalsy(item); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment