that number was concatenated to sum. Remember tha t the + sign works as a concate -
nation op erator when applied to strings.
Mike: But sum isn’t a string.
Professor: As you’ll learn shortly, it isn’t necessary that both operands be strings in
order for the concatenation to take place.
However, let me ask you a question. Why do you think the loop didn’t stop when you
entered zero, and what should you enter if you want it to stop?
Maria: Let me think. Since a return value of prompt() is a string, entering a zero
returns the string "0", which is not a falsy value. We need a falsy value to stop the
loop. I think that we shouldn’t enter anything, just press
OK. If w e d o that, the return
value w ill be an empty string (""), which is a falsy value.
Professor: That’s right.
Mike: Why did hitting
Cancel stop the loo p? And when I hit Cancel right away,
before entering any numbers, the result was NaN. Why is that?
Professor: If y ou press
Cancel, then the prompt() function returns null, which is
a falsy value. When you entered no numbers, sum and counter both remained zero.
Recall tha t dividing zero by zero is not defined and there fore returns N aN.
Now we need a mechanism that will enable us to manipulate data types explicitly.
7.4 Type Conversions
Professor: We’ve already seen that JavaScript is very flexible about types of values.
When, for example, JavaScript exp ects a Boolean value, you can supply any type
of value and JavaScript will convert it to a Boolean value. Some values, which we
named truthy, convert to true, and others, which we named falsy, convert to false.
The same goes for othe r types. If, for exam ple, JavaScript wants a numbe r, then it will
convert any value that is not a number to a number.
There are two th ings that you need to know about type conversions: first, to wh at
value does a value convert, and second, when does the conversion occur. For the sake
of co mpleteness, let us summarize th e most basic conversions in the following table.
Value Converts to:
String Number Boolean
undefined "undefined" NaN false
null "null" 0 false
true "true" 1
false "false" 0
"" (empty string) 0 false
" " (string with one or more spaces) 0 true
" 42 " (numeric string) 42 true
140 Meeting 7. Controlling Program Flow