a == 0 || b == 0
Put dierently, it will return true if either a is zero or b is zero or both are zero.
The last of the Boolean operators is logical NOT (!), which inverts the value of the
expression. T hat m eans it makes false from tru e a nd vice versa. You p la ce this
operator before a Boolean exp ression whose value y ou want to invert. For example, if
the value of x is false, then the expression !x w ill return true.
By the way, because the logica l NOT operator operates on a single value, it is called
a una ry operator. As you have probably noticed, most ope rators combine two values
and are hence called binary. This property of operators is called arity.
Operations with Strings
Professor: Let me now answer your question, Maria. You asked what was the dif-
ference between the literals 3.14 a nd "3.14". You already know tha t, althou gh both
hold the same value, the first one is a number while the second one is a string.
Mike: But are the values really the same? I mean, the second one has quotes.
Professor: Quotes are not part of the value. T hey are just part of a string literal and
they tell the JavaScript interpreter that the value between them is a string type. You
can try and write both values to the browser w indow:
document.write(3.14); //Writes 3.14
document.write("3.14"); //Writes 3.14
In both cases the value 3.14 appears in the window without quotes. So, w hat’s the
dierence, you ask? Let’s try the following code:
document.write(3.14 + 1); //Writes 4.14
document.write("3.14" + 1); //Writes 3.141
As expected, the first line writes 4.14 to the wind ow. The second one, however,
will produce 3.141. That’s because the plus sign be haves dierently with strings—it
becomes the concatenation operator, which concatenates strings even if they contain
numbers.
Relational operators also behave dierently with strings as they do with numbers.
Consider, for example, the next two lines of code:
document.write("mountain" > "molehill"); //Writes true
document.write("2" < "14"); //Writes false
The first line writes true no t because a mountain is bigger than a molehill, of course.
It writes true because, alphabetically, a mountain comes af te r a molehill. Relational
operators compare strings alphabetically.
6.5. Operators a nd Expressions 119
Similarly, the second line writes false bec ause, alphabetically, 2 comes after 14.
Maria: Why is that so?
Professor: When comparing strings alphabetically, only the first characters of both
strings are used in com parison. If they a re equal, th en the second characters of both
strings are compared, and so forth. This continue s until two dierent characters are
found or strings are equal. In that sense 2 c omes a fter 14 just like “n” comes after
“me” in a dictio nary.
Maria: Yes, but how do I know that 2 comes after 1 in the alphabet? And how are
numbers related to letters?
Professor: Now you know that 2 comes after 1.
OK, seriously. Every character is stor ed in a computer m emory as an integer, also
called a character code. When JavaScript compares characters, it actually compar es
their ch aracter codes. Which ch aracter is re presented by which code is defined by the
Unicode encoding. If you are interested, you can check the table at
unicode-table.com.
For example , the c haracter 1 has the hexadecimal code 31 (decim al 49) and 2 has the
hexadecimal code 32 (decimal 50). Le tters have bigger codes so any number will
generally compare as be ing smaller than a ny letter.
Although spaces seldom make a dierence in Java Script code, it is very important that
you be aware of spaces within strings, wh ic h are cha racters in their own right. The
next expression, f or example, evaluates to false because of an extra space at the end of
the second string:
"I’m different" == "I’m different " //Returns false
Likewise, two spaces are dierent from one:
" " != " " //Returns true
Assignment Operator
Professor: It’s time to dr aw your attention to the fact th at none of the operators we’ve
discussed so far has any side eects. All variables involved in a computation retain
their p revious values intact. The question arises: how can a computer program work if
nothing it does leaves any traces behind? Th at’s w hy we ne ed the assignment operator
(=), which can copy the value returne d by an expression on its right-h and sid e to a
variable on its lef t-hand side. Perh aps you will recall that what we can put to the left
of an assignment oper ator is called lvalue. For now, only variables can be lvalues, but
you’ll see late r that there are some other expr essions that can act as lvalues as well.
This is the syntax of using the assignment operator:
lvalue = expression
120 Meeting 6. Behavior
Maria: What about document.write()? It has a side eect, doesn’t it?
Professor: That’s no t a type of side eect tha t I had in mind. The document.write( )
function writes a value of an expression to the browser window, which only the user
can rea d. The code cannot r ead this value back, so the value is lost as concerns the
JavaScript pro gram. Besides, document.write() is not an operator.
Back to the assignment o perator. Because the value of expression has to be eval-
uated before it can be cop ie d to lvalue , it comes as no surprise that the assignment
operator has alm ost the lowest precedence o f all the operator s. Besides, the = ope ra-
tor has right-to-left associativity, which enable s you to set several lvalues to the same
value in a single expression. For example, you can set variables x, y, an d z to zero
this way:
x = y = z = 0
Mike: Does the assignment operator also return a value as other operators do?
Professor: Of course it does. Otherwise th e above multiple assignment exp ression
wouldn’t work. The assign ment op erator returns the value that is being assigned. For
example, the expression z = 0 returns zero. In the above example, this expression
is evaluated first because of the right- to-left associativity of the assignment operator.
Next, the returned zero is assigned to y. This assignment also returns zero, which is
finally assigned to x.
Shorthand Operators
Professor: Some operations ar e very common in computer programs, and to make
life easier for programmers there exist shortened notations for them. For example, if
you want to multiply x by 2 so that x will actu ally receive the new, multiplied value,
you should not only multiply x by 2 but also store the result back to x:
x = x * 2
You could, however, use the shorthand operator *= to do the same:
x *= 2
In fact, a ll five arithmetic operators have their corresponding shorthand form:
lvalue op = expression
where op can be replaced b y any one of the operators +, -, /, *, or %. The above
syntax actually means th is:
lvalue = lvalue op expression
You will often increase or decrease a value by one:
6.5. Operators a nd Expressions 121
counter = counter + 1 //Increases counter by one
counter = counter - 1 //Decreases counter by one
Using a shorthand no ta tion, you can rewrite the last two lin es as:
counter += 1 //Increases counter by one
counter -= 1 //Decreases counter by one
You can make them even shorter:
counter++ //Increases counter by one
counter-- //Decreases counter by one
Operators ++ and -- are used very ofte n to increase or decrease th e value of a variable
by one. They are called in crem ent and decrem ent operators, respe ctively. A s you can
see, they are u nary operators. Both can be placed either before or a fter a variable with
a slight diere nce in oper ation. In both cases th e value of a variable is chan ged but
if an operator is placed after a variable, it retur ns the old value. Only if an operator
is placed before a variable, it returns the updated value. Consider, for example, the
following example:
var x = 10;
var y, z;
y = ++x;
z = x++;
What will be the final values of the variables x, y, and z when the code executes?
Maria: Can y ou declare several variables with a single var keyword? I also noticed
that yo u initialized x while declaring it.
Professor: That’s right. You can give a variable an initial value right away, and you
can declare many variables using a single var keyword, provided you separate indi-
vidual declarations by commas.
So what do you think will be the final values in the above example?
Maria: Beca use x was incremented twice, it should be 12, and because the expression
++x returns the new, incremented value of x, I think y will be set to 11.
Professor: You said the incremented value of x was 12. So why 11?
Maria: Yes, but in the third line x is only incremented for the first time. The fourth
line has not even started yet.
Professor: Absolutely. Go on.
122 Meeting 6. Behavior
Maria: In the fourth line x is incremented for the second time, but the expression x++
returns its old value, the one it had before this second increment. He nce, z will be 11
as well.
Professor: Per fect.
The Conditional Operator
Professor: It’s nice when a computer can undertake some tedious calculations for you,
but it would be even nicer if it could make decisions based on those calculations. For
one thing, that is what computers usu ally do. Even tasks as simple as calculating the
absolute value o f a number involves dec isions whether or not to multiply the number
with minus one. The con ditional operator (?:) allows a program to make decisions
like that. It works with three operands, which makes it a ternary opera tor. Because it is
the only one of its kind, it is sometimes called simply the ternary operator. Although
you will see the cond itional operator written as ?:, it a ctually does not appear quite
like that in code because one of the three operands goes between the symbols ? and :.
With the conditional operator, you write expressions using the following syntax:
condition ? if_true : if_false
The operator works as follows. First, condition is evaluated, and if its value is
true, th en if_true is evaluated and its value is retur ned. However, if condition is
false, then if_false is evaluated and its value is returned. Notice that only one of
the expressions if_true and if_false is actually evaluated as p art of a conditional
operator evaluation.
Basically, this is it. Could you now write an expression that will replace the value of
x with its absolute value?
Mike: condition will probably be some thing like x < 0 because the value should
only change if it is negative. The n, in place of if_true , I would put x *= -1. And
that’s it.
Professor: You’re close but that won’t work, I’m afraid. As for a ny operator, you
must provide all the ne cessary operands for the conditional ope rator as well. If they
are three, then they are three. You sho uld put in something as a third operand even if
there’s nothing to do when condition is f alse. Besides, it is not a common practice
to make assignments within the conditional o perator although it is not wrong. It’s
better to let the operator just return the right value and then assign that value to an
appropriate variable via the assignment operator. The next expression replac es the
value of x with its absolute value:
x = x < 0 ? -x : x
This works because the conditional operator has precedence over the assignment op-
erator, and the less-than operator has precedence over the conditional op erator.
6.5. Operators a nd Expressions 123
..................Content has been hidden....................

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