Skip to content

Instantly share code, notes, and snippets.

@skoshy
Last active January 26, 2018 17:07
Show Gist options
  • Save skoshy/69a7951b3070c2e2496d8257e16d7981 to your computer and use it in GitHub Desktop.
Save skoshy/69a7951b3070c2e2496d8257e16d7981 to your computer and use it in GitHub Desktop.
Determines if any value is "falsy" in JavaScript
// 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]));
function isTruthy(item) {
return !isFalsy(item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment