I use the following code currently
if (oldValue) ...
It works well in case oldValue is null, but in case it is 0, it also returns false, when I expect true. So, how should I check for null value? I was thinking about
if (oldValue!=null) ...
but it doesn’t work as I’ve expected.
To answer your question directly, if your allowed values are
0and1theifstatement should look like:This is (in my opinion) the clearest way to state which values are allowed.
For a more details explanation see below:
This has to do with truthy and falsy values.
nullevaluates tofalse, as do0,"",undefinedandNaN, these are called falsy values.Likewise, some values evaluate to
true. Such as:"a string","0"(non empty string “0”), any number other than0(including negative numbers),Arrays andObjects (even empty ones). These are truthy values.There are some unexpected results:
but:
In practice you should always use the identity operator
===instead of equality (==). This ensures that you know what type your variable is expected to be (String, Number, Object) and what the exceptional states are.Some examples:
0. Coincidentally this is a falsy value.parseIntorparseFloat– the special caseNaN(check withisNaN()). Coincidentally this is a falsy value.indexOf– the special case is-1(because0is a valid index). This is not a falsy value, butif(str.indexOf(substr))is most certainly wrong because it is unclear the author knows about the possibly allowed value0(which is falsy)The point here is: the special cases usually are well defined. Harnessing that allows you to always use the identity operator
===. The equality operator==and falsiness is a common source of bugs.For reference: