Tải bản đầy đủ (.pdf) (27 trang)

Expressions and Operators

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (238.53 KB, 27 trang )

Chapter 5. Expressions and
n JavaScript. If you are
familiar with C, C++, or Java, you'll notice that the expressions and operators in
able to skim this chapter quickly. If you are not
s, like these:
// An object literal
[2,3,5,7,11,13,17,19] // An array literal
function(x){return x*x;} // A function literal
i
sum
The value of a literal expression is simply the liter tself. The value of a variable
ariable contains or refers to.
terestin ting)
p s can be created by combining simp . F e saw that
7 is an expression and i is an expression. T
of this expression is determined by adding the values of the two sim
expressions. The + in this example is an operator that is used to com
to complex expression. Another ope , which i
ion. For example:
) - sum
Operators
This chapter explains how expressions and operators work i
JavaScript are very similar, and you'll be
a C, C++, or Java programmer, this chapter tells you everything you need to know about
expressions and operators in JavaScript.
5.1 Expressions
An expression is a phrase of JavaScript that a JavaScript interpreter can evaluate to
produce a value. The simplest expressions are literals or variable name
1.7 // A numeric literal
"JavaScript is fun!" // A string literal
true // A boolean literal


null // The literal null value
/java/ // A regular expression literal
{ x:2, y:2 }
// The variable i
// The variable sum
al value i
expression is the value that the v
These expressions are not particularly in
ex
g. More complex (and interes
le expressionsression or example, w
1. he following is also an expression:
i + 1.7
The value pler
bine two expressions
in
expressions by subtract
a more rator is - s used to combine
(i + 1.7
This expression uses the - operator to subtract the value of the sum variable from the
value of our previous expression, i + 1.7. JavaScript supports a number of other
operators besides + and -, as you'll see in the next section.
5.2 Operator Overview
If you are a C, C++, or Java programmer, most of the JavaScrip rs should already
be familiar to you. Table 5-1
t operato
summarizes the operators; you can refer to this table for
fe that most operators are represented by punctuation characters such as +
and . Some, however, are represented by keywords such as delete .
ey tors are regular operators, just hose express

are simply expressed using a more readable and less succinct sy
In this table, the column labeled "P" gives the operator precedence and the column
the operator associativity, w e L (le
ciativity, the subsections that
le explain these concepts. The operators themselv
Table 5-1. JavaScript operators
re rence. Note
=
wo
and instanceof
ed with punctuation; theyK rd opera like t
ntax.
labe
left). If you do not already understand preceden
led "A" gives hich can b
ce and asso
ft-to-right) or R (right-to-
follo
following that discussion.
w the tab es are documented
P A Operator
nd
type(s)
n performed
Opera
Operatio
15 L
.
identifier
cess

object,
Property ac
L
[]
array, integer index Array
L
( )
function,
arguments
Function call
R
new
constructor call Create new object
14 R
++
lvalue
Pre- or post-increment
(unary)
R
--
lvalue
Pre- or post-decrement
(unary)
R
-
number ion)Unary minus (negat
R
+
number p)Unary plus (no-o
R

~
integer
Bitwise complement
(unary)
R
!
boolean
Logical complement
(unary)
Table 5-1. JavaScript operators
P A Operator
Operand
type(s)
Operation performed
R
delete
roperty
lvalue
Undefine a p
(unary)
R
typeof
ype (unary) any Return data t
R
void
any
Return undefined value
(unary)
13
/, %

n, division,
L
*,
numbers
Multiplicatio
remainder
12 ionL
+, -
numbers Addition, subtract
L
+
strings String concatenation
11 L
<<
integers Left shift
L
>>
integers
Right shift with sign-
extension
L
>>>
integers
Right shift with ze
extension
ro
10 L
<, <=
numbers or
strings

Less than, less than or
equal
L
>, >=
numbers or
strings
Greater than, greater than
or equal
L
object,
Check object type
instanceof
constructor
L string, object
Check whether property
in
exists
9 L
==
any Test for equality
L
!=
any Test for inequality
L
===
any Test for identity
L
!==
any Test for non-identity
8 L

&
integers Bitwise AND
7 L
^
integers Bitwise XOR
6 L
|
integers Bitwise OR
5 L
&&
booleans Logical AND
Table 5-1. JavaScript operators
P A Operator
Operand
type(s)
Operation performed
4 L
||
booleans Logical OR
3 R
?:
boolean, any,
any
Conditional operator (
operands)
3
2 R
=
lvalue, any Assignment
R

*=, /=, %=, +=, -=, <<=, >>=,
>>>=, &=, ^=, |=
lvalue, any
Assignment with
operation
1 L
,
any Multiple evaluation
ts a number of unary operators, which convert a
plex expression. The - operator in the
unary operator that performs the operation of negation on the operand
ternary operator, the conditional operator ?:, which
combines the value of three expressions into a single expression.
xpressions, you must pay attention to the data types that
are being passed to operators and to the data types that are returned. Different operators
is not legal in
JavaScript. Note, however, that JavaScript tries to convert expressions to the appropriate
ble, so the expression
"3" * "5" is legal. Its value is the number 15,
ot the string "15". We'll consider JavaScript type conversions in detail in Section 11.1
5.2.1 Number of Operands
Operators can be categorized based on the number of operands they expect. Most
JavaScript operators, like the + operator we saw earlier, are binary operators that
combine two expressions into a single, more complex expression. That is, they operate on
two operands. JavaScript also suppor
single expression into a single, more com
expression -3 is a
. Finally, JavaScript supports one 3
5.2.2 Type of Operands
When constructing JavaScript e

expect their operands' expressions to evaluate to values of a certain data type. For
example, it is not possible to multiply strings, so the expression "a" * "b"
type whenever possi
n .
Notice that the assignment operators, as well as a few other operators, expect their
lefthand expressions to be lvalues. lvalue is a historical term that means "an expression
that can legally appear on the lefthand side of an assignment expression." In JavaScript,
Furthermore, some operators behave differently depending on the type of the operands.
Most notably, the + operator adds numeric operands but concatenates string operands.
Also, if passed one string and one number, it converts the number to a string and
concatenates the two resulting strings. For example, "1" + 0 yields the string "10".
variables, properties of objects, and elements of arrays are lvalues. The ECMAScript
specification allows built-in functions to return lvalues but does not define any built-in
an
s whether the comparison is true or not. For example, the expression a
< 3 returns true if the value of variable a is in fact less than 3. As we'll see, the boolean
mparison operators are used in if statements, while loops, and for
ops -- JavaScript statements that control the execution of a program based on the results
of evaluating expressions that contain comparison operators.
Table 5-1
functions that behave that way.
Finally, note that operators do not always return the same type as their operands. The
comparison operators (less than, equal to, greater than, etc.) take operands of various
types, but when comparison expressions are evaluated, they always return a boole
result that indicate
values returned by co
lo
5.2.3 Operator Precedence
In , the column labeled "P" specifies the precedence of each operator. Operator
erators with higher

mbers.
ing expression:
The multiplication operator * has a higher precedence than the addition operator +, so the
erformed before the addition. Furthermore, the assignment operator =
the assignment is performed after all the operations on the
nd subtraction, and assignment has very low precedence and is almost always performed
5.2.4
In Tabl
precedence controls the order in which operations are performed. Op
numbers in the "P" column are performed before those with lower nu
Consider the follow
w = x + y*z;
multiplication is p
has the lowest precedence, so
righthand side are completed.
Operator precedence can be overridden with the explicit use of parentheses. To force the
addition in the previous example to be performed first, we would write:
w = (x + y)*z;
In practice, if you are at all unsure about the precedence of your operators, the simplest
thing is to use parentheses to make the evaluation order explicit. The only rules that are
important to know are these: multiplication and division are performed before addition
a
last.
Operator Associativity
e 5-1, the column labeled "A" specifies the associativity of the operator. A valu
ecifies left-to-right associativity, and a value of R specifies right-to-left
tivity. The associativity of an operator specifies the order in which operations of
e
of L sp
associa

the sam precedence are performed. Left-to-right associativity means that operations are
eft to right. For example, the addition operator has left-to-right
associativity, so:
w = x
is the s e as:
On the other hand, the following (almost nonsensical) expressions:
z;
q = a?b:c?d:e?f:g;
are equ
x = ~(
w = (x
q = a?
because the unary, assignment, and ternary conditional operators have right-to-left
5.3 A
Having
can sta
Additio
he + operator adds numeric operands or concatenates string operands. If one
a string, the other is converted to a string and the two strings are then
ed to numbers or strings that can be
Subtraction -
e
performed from l
+ y + z;
am
w = ((x + y) + z);
x = ~-~y;
w = x = y =
ivalent to:
-(~y));

= (y = z));
b:(c?d:(e?f:g));
associativity.
rithmetic Operators
explained operator precedence, associativity, and other background material, we
rt to discuss the operators themselves. This section details the arithmetic operators:
n (+)
T
operand is
concatenated. Object operands are convert
added or concatenated. The conversion is performed by the valueOf( ) method
and/or the toString( ) method of the object.
( )
When - is used as a binary operator, it subtracts its second operand from its firs
operand. If used with non-numeric operands, it attempts to convert them to
numbers.
t
Multiplication (*)
Division (/)
rator divides its first operand by its second. If used with non-numeric
t
ating-
Modulo
lo the second operand. That is, it
nds, the modulo operator
to convert them to numbers. The sign of the result is the same as the sign
erand. For example,
5 % 2 evaluates to 1.
While the modulo operator is typically used with integer operands, it also works
, -4.3 % 2.1 evaluates to -0.1.

Unary
When is used as a unary operator, before a single operand, it performs unary
o
Unary
The * operator multiplies its two operands. If used with non-numeric operands, it
attempts to convert them to numbers.
The / ope
operands, it attempts to convert them to numbers. If you are used to programming
languages that distinguish between integer and floating-point numbers, you migh
expect to get an integer result when you divide one integer by another. In
JavaScript, however, all numbers are floating-point, so all divisions have flo
point results:
5/2 evaluates to 2.5, not 2. Division by zero yields positive or
negative infinity, while 0/0 evaluates to NaN.
(%)
The % operator computes the first operand modu
returns the remainder when the first operand is divided by the second operand an
integral number of times. If used with non-numeric opera
attempts
of the first op
for floating-point values. For example
minus (-)
-
negation. In other words, it converts a positive value to an equivalently negative
value, and vice versa. If the operand is not a number, this operator attempts t
convert it to one.
plus (+)
For symmetry with the unary minus operator, JavaScript also has a unary plus
operator. This operator allows you to explicitly specify the sign of numeric
literals, if you feel that this will make your code clearer:

var profit = +1000000;
In code like this, the + operator does nothing; it simply evaluates to the value of
for non-numeric arguments, the + operator has
ent to a number. It returns NaN if the argument
single operand, which must be a
rty of an object. If the value of this
ber, the operator first attempts to
convert it to one. The precise behavior of this operator depends on its position
For example, the following code sets both and to :
i = 1;
nter
insert a line break between the post-increment or post-
its argument. Note, however, that
the effect of converting the argum
cannot be converted.
Increment (++)
The ++ operator increments (i.e., adds 1 to) its
variable, an element of an array, or a prope
variable, element, or property is not a num
relative to the operand. When used before the operand, where it is known as the
pre-increment operator, it increments the operand and evaluates to the
incremented value of that operand. When used after the operand, where it is
known as the post-increment operator, it increments its operand but evaluates to
the
unincremented value of that operand. If the value to be incremented is not a
number, it is converted to one by this process.
i j 2
i = 1;
j = ++i;
But these lines set i to 2 and j to 1:

j = i++;
This operator, in both of its forms, is most commonly used to increment a cou
that controls a loop. Note that, because of JavaScript's automatic semicolon
insertion, you may not
decrement operator and the operand that precedes it. If you do so, JavaScript will
treat the operand as a complete statement by itself and will insert a semicolon
before it.
Decrement (--)
The -- operator decrements (i.e., subtracts 1 from) its single numeric operand
which must be a variable, an element of an array, or a property of an object. If the
value of this variable, element, or property is not a number, the operator first
attempts to convert it to on
,
e. Like the ++ operator, the precise behavior of --
depends on its position relative to the operand. When used before the operand, it
the operand but returns the undecremented value.
5. E
This se
operato
and tu .
As we'
decrements and returns the decremented value. When used after the operand, it
decrements
4 quality Operators
ction describes the JavaScript equality and inequality operators. These are
rs that compare two values to determine whether they are the same or different
re rn a boolean value (true or false) depending on the result of the comparison
ll see in Chapter 6, they are most commonly used in things like if statements and
ps, to control the flow of program execution.
Equality (==) and Identity (===)

and === operators check whether two values are the same, using two different
ons of sameness. Both operators accept operands of any type, and both return
for loo
5.4.1
The ==
definiti
tru if
known as the identity operator, and it check
usin a ; it
checks
that allo
The identity operator is s dized by ECMAScript v3 and implemented in JavaScript
tors. Be sure you understand the differences between the assignment,
ality, and identity operators, and be careful to use the right one when coding!
Alt u
confusi dentical to"
for
=
In JavaScri is case,
two separa
values are n ey
contain the m
exactly the m
On the othe h
that two variab
never equal or
that contain ref
same object, a
e their operands are the same and false if they are different. The === operator is
s whether its two operands are "identical"

g strict definition of sameness. The == operator is known as the equality operator
whether its two operands are "equal" using a more relaxed definition of sameness
ws type conversions.
tandar
1.3 and later. With the introduction of the identity operator, JavaScript supports =, ==,
and === opera
equ
ho gh it is tempting to call all three operators "equals," it may help to reduce
on if you read "gets or is assigned" for =, "is equal to" for ==, and "is i
== .
pt, numbers, strings, and boolean values are compared by value. In th
te values are involved, and the == and === operators check that these two
ide tical. This means that two variables are equal or identical only if th
sa e value. For example, two strings are equal only if they each contain
sa e characters.
r and, objects, arrays, and functions are compared by reference. This means
les are equal only if they refer to the same object. Two separate arrays are
identical, even if they contain equal or identical elements. Two variables
erences to objects, arrays, or functions are equal only if they refer to the
rray, or function. If you want to test that two distinct objects contain the
same propertie have to
check the prop or equality or identity. (And, if any of the
properties e ve to decide how deep
you want the comparison to go.)
The following rules are used to determine whether two values are identical according to
x If the two values have different types, they are not identical.
value
x If both values are strings and contain exactly the same characters in the same
t
g

haracter basis, and it assumes
that all strings have been converted to a "normalized form" before they are
" reference page in the core reference
section of this book for another way to compare strings.
l. If
are used to determine whether two values are equal according to the
== operator:
x If the two values have the same type, test them for identity. If the values are
her is a string, convert the string to a
number and try the comparison again, using the converted value.
object to a primitive and try the comparison again. An object is converted
to a primitive value by either its
toString( ) method or its valueOf( )
f core JavaScript attempt valueOf( )
)
conversion, except for the Date class,
which performs toString( ) conversion. Objects that are not part of core
s or that two distinct arrays contain the same elements, you'll
erties or elements individually f
or lements are themselves objects or arrays, you'll ha
the
=== operator:
x If both values are numbers and have the same value, they are identical, unless
either or both values are NaN, in which case they are not identical. The NaN
is never identical to any other value, including itself! To check whether a value is
NaN, use the global isNaN( ) function.
positions, they are identical. If the strings differ in length or content, they are no
identical. Note that in some cases, the Unicode standard allows more than one
way to encode the same string. For efficiency, however, JavaScript strin
comparison compares strictly on a character-by-c

compared. See the "String.localeCompare( )
x If both values are the boolean value true or both are the boolean value false,
they are identical.
x If both values refer to the same object, array, or function, they are identica
they refer to different objects (or arrays or functions) they are not identical, even
if both objects have identical properties or both arrays have identical elements.
x If both values are null or both values are undefined, they are identical.
The following rules
identical, they are equal; if they are not identical, they are not equal.
x If the two values do not have the same type, they may still be equal. Use the
following rules and type conversions to check for equality:
o If one value is null and the other is undefined, they are equal.
o If one value is a number and the ot
o If either value is true, convert it to 1 and try the comparison again. If
either value is false, convert it to 0 and try the comparison again.
o If one value is an object and the other is a number or string, convert the
method. The built-in classes o
conversion before
toString(

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×