Mike: Is there a way to get and write the type of a value?
Professor: There is, actually. You can get the type of a value using the typeof
operator. You simply put it before the value you want to test:
var txt = "I’m plain text";
var x = 4;
document.write(typeof txt); //Writes string
document.write(typeof NaN); //Writes number
document.write(typeof x); //Writes number
document.write(typeof 1.2e-14); //Writes number
document.write(typeof "3.14"); //Writes string
document.write(typeof true); //Writes boolean
document.write(typeof "NaN"); //Writes string
document.write(typeof undefined); //Writes undefined
Because the typeof operator returns a description of a ty pe in a text for m, the type of
the value returned by the typeof operator is string:
document.write(typeof typeof 42); //Writes string
Maria: I wonder if there is any practical use for knowing the types of values. I mean,
what’s the dierence between 3.14 and "3.14"?
Professor: The behavior of both can be quite dierent. To find out how, we first need
to know about operators in JavaScript.
6.5 Operators and Expressions
Professor: What a computer program does is make operations on values to produce
new values. The operations are executed by means of operators, and the values on
which they operate are called operands. However, before we plunge into the world
of JavaScript operators let’s define an expre ssion. An expression can be viewed as a
phrase that a JavaScript interpreter can evaluate in order to produce a value. We say
that an expression returns a value.
Accordin g to this definition, an expr ession can be as simple as a single constant or
literal value, a certain language keyword, or a variable reference. These are called
primary expressions. For example, the following are a ll primary expressions:
3.14 //Returns 3.14
x //Returns the value stored in x
true //Returns true
"something blue" //Returns "something blue"
Primary expressions can be used to build more complex expressions by means o f
appropriate op erators. Some of them we have alre ady met. For example:
114 Meeting 6. Behavior
19 + 23 //The + operator for adding two operands.
//The expression returns 42.
typeof true //The typeof operator for determining the type of
//an operand. It returns "boolean".
Consider, for example, the following expression. What value does it return?
2 * 4 + 3 * 3
Maria: 17.
Professor: And how do you know that?
Maria: Because two times four equ als eight, thr ee times three equa ls n ine, and, finally,
eight p lus nine equals 17.
Professor: I see you are alread y familiar with operator precedence. Just as you learned
in primary school that multiplication is done befor e addition, JavaScript precisely de-
fines which operato r has precedence over which.
What about the next expression? What value does it return?
5 - 4 - 3
Mike: -2.
Professor: Because you computed it righ t, I assume you already know ab out op erator
associativity. Associativity defines w hether oper ators with the same prec edence are
executed from left to right or from right to left. Subtrac tion has left-to-right associa-
tivity, as do most of the JavaScript operators that take two operands. You will find
JavaScript ope rators organized by precedence, with additio nal information about their
associativity in the JavaScript Mini Reference on page 373.
If yo u don’t like precedence and associativity of an operator, you can always change
the order of execution using parentheses—the op erators within parentheses will be
evaluated first. For example, if you want th e subexpression 4 - 3 in the above ex-
pression to be evaluated first, then you simply enclose it in pa rentheses:
5 - (4 - 3) //Returns 4
Arithmetic Operators
Professor: I would now like to go through some of the JavaScript operators that you
will most likely use in your programs. First, there are arithm etic operators, and you
won’t be surprised that they include operator s for addition (+), subtractio n (-), mul-
tiplication (*), and division (/). As you alre ady know from primar y school mathe-
matics, the second two have prec edence over th e first two, and all have left-to-right
associativity. The subtraction operator c an be used as a negative sign operator as well,
6.5. Operators a nd Expressions 115
in w hich case it has the highest precedence. For example, the following expression
returns -12:
2 * -6 //Returns -12
It is somehow self-evident that you should evaluate the subexpression -6 first, and
then multiply it by two. There’s simply no other way of seeing it. The good news is
that many rules of precedenc e and associativity are somehow logical and need no t be
learned explicitly.
The only arithmetic opera tor that you may not have hea rd of befo re is the remainder
operator, which re turns the remainder after a division. The operator’s symbol is a
percent sign (%). Although in JavaScript this operator operates on integers as well as
on non-integers, it is primarily used with integers (the so-called Euclidean division).
Consider, for example, that you have to divide 41 candies fairly among six childr en.
Each child gets six candies and ve will be left over as a remainder. This is summa-
rized in the next expression:
41 % 6 //Returns 5
You should be careful, though, when you use the remain der operator with negative
numbers. In n umber theory, this operator is called the modulo opera tor where the
remainde r is always positive. That said, in JavaScript the sign of the result is the
same as the sign of the dividend and can be negative. T hings become even more
confusing because the sign can be computed dierently in other languages. In Python,
for example, the same operator returns a remainder wh ose sign is the same as the sign
of the divisor.
Relational Operators
Professor: The next group of operators test for a r elationship between two values and
return the Boolean value true if the relationship holds and false if the relationship
doesn’t hold. Basically, you can view the relationa l operations as asking questions
like: “Is the left-hand side value greater than the right-hand side value?” or Are b oth
sides equal?” If the answer is “yes, then the return value is true, or else, if the
answer is “no , the r eturn value is false. Here’s a table of all th e relational operators:
Operator Test of Relationship
< Less tha n
<= Less than or equal to
> Greater than
>= Greater than or equa l to
== Equal to
!= Not equal to
=== Strictly equal to
!== Strictly no t equal to
116 Meeting 6. Behavior
Notice that some operators are composed o f two, or even three symbols. You should
never p ut a space between th em or you will brea k an operator into two or three opera-
tors.
The common use of re la tional operators ma y be trivial, but still, let me give you som e
examples to warm you up. Can you tell me wha t values the fo llowing three expressions
return?
10 < 2
6 >= 6
6 != 4
Maria: They return false, true, and true.
Professor: Precisely. What about the n ext one? Suppose that x has bee n given the
numeric value 4.
10 < x < 20
Maria: That’s false .
Professor: Unfortunate ly it isn’t. But let’s save the explanation for the next meeting.1
Did you notice in the above table that there are two dierent o perators testing whether
two values a re the same? They use, h owever, two slightly dierent definitions of what
“the same” means. The first one, the equality operator (==), represents a more re la xed
test of sameness. It compa res values and doesn’t require the types to be the same. For
example, the following two expr essions both return true even though the types, or
even values, are dierent:
42 == "42" //Returns true
undefined == null //Returns true
The strict equality op erator (===), however, retu rns false if the types don’t match:
42 === "42" //Returns false
undefined === null //Returns false
The inequality (!=) and strict inequality (!==) opera tors work in just the opposite way:
42 != "42" //Returns false
42 !== "42" //Returns true
There’s one very special case where equal is not equal, which involves the NaN value.
NaN will not co mpare equa l to any other value, includin g itself. Consider the next two
expressions:
1If you’re curious, you can find the explanation on page 145.
6.5. Operators a nd Expressions 117
NaN === NaN //Returns false
NaN !== NaN //Returns true
That’s bizarre. As a consequence, if you want to check whether a variable has received
the NaN value, yo u must compare a variable to itself:
x !== x //Returns true if and only if x is NaN.
Mike: Excuse me, but why are null and undefined equal? Is there a rule or must
you learn it by heart?
Professor: Both. It’s a rule that you m ust learn by hea rt. You are going to hear about
this the next time when we talk about type conversions.2
Logical Operators
Professor: There exist three logical operators to perform Boolean algebra. Most often
you will use them to combine two or more relational expressions to build more com-
plex expressions. You may have already heard of them, but just in case, let me review
them b riefly. In common for all of the thre e operators is that they operate on Boolean
values true and false, and they return Boolean values as well.
The first on e is logical AND (&&), which returns true if and only if both of its operan ds
are true. For example, the following expression re turns true only if bo th a and b are
equal to zero:
a == 0 && b == 0
Mike: Can you w rite this shorter: a && b == 0?
Professor: You can, but it means something completely dierent. If yo u check the
operator table in the JavaScript reference on page 373, you will find out that the equal-
ity operator (==) has precedence over log ic al AND (&&) . Therefore, the expression
b == 0 is evaluated first. The value of this expression is then combined with the
value of the variable a through the log ic al AND operator. Your expression will thus
evaluate to true if and only if b is zero an d a is true. I must warn you that JavaScript
operators are very precisely defined and you c annot build expressions relying on your
intuition.
The second Boolean o perator is logical OR ( ||). It returns true if any one o f the two
operan ds evaluates to tr ue.
For example, the following expression will return true if at least one of the variables
a and b is zero:
2You can learn why null and undefined are equal on page 144.
118 Meeting 6. Behavior
..................Content has been hidden....................

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