Lessons · TypeScript · what counts as true
What counts as true
Only six values are falsy: false, 0, '', null, undefined and NaN. Everything else is truthy, including '0', 'false', [] and {}.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
if (value) is written a hundred times a day, and it silently treats a real 0 or an empty string as missing while treating the text '0' as present.
How to think about it
Ask the question you mean. Missing: value == null. Empty text: value.length === 0. Zero: value === 0. Use bare truthiness only when 'falsy' is exactly the test you want.
Worked example
console.log(Boolean("0"), Boolean(0));true false: a non-empty string is truthy, the number 0 is not.console.log(Boolean(" "), Boolean(""));true false: whitespace has length.console.log(Boolean([]), Boolean({}));true true: empty containers are truthy in JavaScript.console.log(Boolean(null), Boolean(undefined), Boolean(NaN));false false false.
Your turn
Is the text non-empty, without a truthiness surprise?
if (text.length 0)
Solve one with the tests running
The trap
Values from forms are text, so if (value) is true for '0' and 'false'. Convert first, or test the length.