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
"three pi gs" (non -numeric string) NaN true
0 "0" false
-0 "0" false
NaN "NaN" false
Infinity "Infinity" true
-Infinity "-Infinity" true
42 (any n on-zero number) "42" true
The conversions are pretty straightforward. You are already familiar with the last
column, which covers truthy and falsy values. The second column lists co nversions
to strings, w hich don’t change values at all except for negative zero where the minus
sign is lost.
Conversions to numbers, which you find in the third column , are a just a little bit more
knotty. I mentioned the other day that null represented an expected absence of value.
You will therefore not find it surprising that this value is converted to zero. Next,
true in digital logic usu ally denotes a switched-on switch and is often represen te d
by a logical one. On the other hand, fals e denotes a switched-o switch and is
represented by a logical zero (the absence of elec trical current, if you want). If you
can acce pt that, then these two conversions start looking quite obvious, too.
The last category listed in the third column shows conversions from strings. Strings
that co ntain pure num eric data, possibly with lea ding or trailing spaces, simply convert
to the number found in quotes. Next, an empty string converts to zero. This is not hard
to remember because a n empty string is a falsy value just like a zer o is. Finally, any
string that cannot be converted to a nu mber becomes NaN.
Maria: Now I’m confused. I remember earlier this morning when we ta lked about
truthy and falsy values. You said something to th e eect that the expression x !=
null is only false if x is null or undefined. Is that so?
Professor: That’s right.
Maria: What if x is zero, for example? Zer o is a falsy value and null is a falsy value.
So they should not be dierent since they both convert to false. I therefore think that
the expression 0 != null should return false.
Professor: I see your point. It’s true that both zero and null convert to fal se any
time such conversion occurs. However, conversions do not always occur. Relational
operators do not re quire Boolean values as their operand s, so the tr uthy and falsy
conversions do not occur in connection with the inequality operator. That’s why a
compariso n of zero and null evaluates to not equal.
Let’s take a lo ok at the most common situations in which type conversions take p la ce.
The basic rule is that JavaScript a lways converts values to the type it wants in a particu-
lar situation. It is straightforward that conditionals and loops require Booleans as their
conditional expressions. Logica l operators also require Booleans a s their operands. In
such cases the truth y and falsy conversions take place.
7.4. Type Conversions 141
Mike: You mean the values are converted to those in the last column of the above
table?
Professor: That’s right. For example, consider the next statement:
if (cond) { /* Do something */ }
The value of cond will invariably be converted to a Boolean value tru e or false,
depending on its original value.
Mike: What if I place some com plex expression in place of a variable? Do all the
variables inside the expression convert to Booleans?
Professor: Oh no . Variables themselves do not change at all. It’s only the return
values of expressions and subexpressions that are converted. What’s more, they are
converted on an as-nee ded basis, respecting the evaluation order as defined by oper-
ator precedence and associativity. If a subexpression can be evaluated without any
type conversion, then it is evaluated so. Only the return value is converted, if that is
necessary, of cour se.
Unlike with Booleans, it is not as obvious what JavaScript wants in th e case of arith-
metic operators. In most cases it wants numbers and converts everything it finds to a
number. A few examples:
false + 2 * true //Returns 2: Booleans convert to numbers
"15" / "5" //Returns 3: strings convert to numbers
"23" - 1 //Returns 22: the string "23" converts to a number
"x" * 5 //Returns NaN: the string "x" can’t convert to a number
13 % "2" //Returns 1: the string "2" converts to a number
When, however, the addition operator is used, it behaves as a concatena tion operator
as soon as at least one of the oper ands is a string. The o ther operan d is then converted
to a string:
var x = "2";
true + " colors" //Returns "true colors"
7 + " brothers" //Returns "7 brothers"
"2" + 5 //Returns "25"
x += 1; //x becomes "21"
x++; //An exception: x becomes a number (i.e., 3)
Notice that the increment operator (++) converts a string to a number even though it is
just a shorthand operator for adding one to the value of a variable.
Explicit Conversions
Professor: There are situations when you want to p erform certain type conversions
explicitly. For instance, in our arithmetic me an example we should have converted
142 Meeting 7. Controlling Program Flow
the number enter ed by the user—which was returned a s a string—to a number before
adding it to the sum. Any idea h ow to do that?
Maria: Perhaps w e could subtract a zero from a string?
Professor: True. As a matter of fact, any basic arithmetic operation other than addition
will do the trick:
number - 0
number * 1
number / 1
And you can use a unary positive sign operator as well:
+number
However, the easiest and the most obvious me thod to perform an explicit type conver-
sion is to use any of the functions Number(), String(), or Boolean().
Number("3.1416") //Returns 3.1426
String(true) //Returns "true"
Boolean("") //Returns false
Going ba ck to our ar ithmetic mean program, you can replac e the while loop condition
with either one of the following two expressions:
number = +prompt("Enter a number:")
number = Number(prompt("Enter a number:"))
Incidenta lly, sometimes you migh t enc ounter the following two conversion expres-
sions:
x + "" //Same as String(x)
!!x //Same as Boolean(x)
Mike: Where does the seco nd one come from?
Professor: Well, remember that the logical NOT operator (!) accepts a Boolean value
and returns a Boolean value as well. In fact, !x returns true if x is falsy and returns
false if x is truthy. If you use the logical NOT once again, yo u finally get true from
a truthy value and false from a falsy value.
Conversions and Relational Operators
Professor: I will conclude today’s meeting with what is prob ably the most important
of all the situations that acco unt for type conversions. These occur in connection with
equality (ine quality) and comparison operators.
7.4. Type Conversions 143
The most straightforward is the strict equality operator (===), which performs no type
conversion whatsoever. The values as well as types on both sides of the o perator
should be equal if you want the operator to return true:
"42" === 42 //Returns false
true === 1 //Returns false
null === undefined //Returns false
The strict inequality operator (!==) is exactly the opposite of the === o perator, and it
perfor ms no type conversion either:
"42" !== 42 //Returns true
true !== 1 //Returns true
null !== undefined //Returns true
The very special case, as you already know, is the NaN value. This value is never equal
to any other value, includ ing itself. Therefore, if y ou want to check whether a value
of x is NaN, you write:
x !== x //Returns true if and only if x equals NaN
The equality ope rator (==) is less strict. Essentially, it works like the strict equality op-
erator except that it a ttempts certain type conversions if it discovers that the operands
are not the same type. The operator uses the following rules:
Values null and undefined are considered equal.
If a number is compared to a string, then a string is converted to a number and
the converted number is used in c omparison.
If either value is true or false it is converted to 1 or 0, respectively, before
used in comparison.
For example, the next comparisons all return true:
null == undefined
5 == "5"
false == "0"
In the last of the above lines, false is converted to th e number zero before the com-
parison is made. Since the types are still dierent, the string "0" is then converted to
the numb er zero and the comparison is performed again. Because both numbe rs are
now the same, the expression returns true.
The ine quality operator (!= ) is of course the exact o pposite of the equality o perator.
Comparisons other than equality and inequality can only be carried out on strings and
numbers. The re are three possible situations:
144 Meeting 7. Controlling Program Flow
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.96.135