Truthy and Falsy Values
Professor: The first line of our la st example could also be written shorter, without a
compariso n but with the same result:
if (x % 2)
You see, JavaScript is quite flexible when it co mes to data types. If it doesn’t like
the type , it implicitly converts it so as to match the requir ement. For example, the
expression x % 2 doesn’t retur n eithe r true or false so, technically, we cannot
use it a s a branching condition, which requ ires a Boolean value. However, know-
ing th at JavaScript implicitly converts zero to false and one to tr ue when it re quires
a Boolean value, we can drop the comparison part of the expression in this particular
case.
But zero is not the only value th at converts to false when a Boolean value is expected.
Altogether, there are five such values:
0
undefined
null
NaN
"" //A string without any character
All these five values work as false, and are, together with the f alse value itself,
called falsy values. All the other values are called truthy values. You have to be
careful, though, when leaving out explicit comp arisons, because results are not always
identical as was the case in our last example. For instan ce, this is how you can test
whether x has been given a value:
if (x != null) ...
In this example, the body of the if statement will be executed only if x is n ot n ull or
undefined. In th e following example, however, the b ody will be executed if x is not
false, or any falsy value, for that matter:
if (x) ...
It is really important that you k now exactly what types of values you expect in your
progr am and what you want to a chieve. For clarity, it is almost always better to use
explicit comparisons, although they may not be required.
while Loop
Professor: Another type of branching is going back upon the same statement again
to repeat portions of your code. A control statement that allows such branching is
called a loop, and one repetition of a statement or statements within a loop is called
134 Meeting 7. Controlling Program Flow