Chapter 5
In This Chapter
Reading and coding JavaScript expressions
Changing values with assignment operators
Thinking logically with comparison operators
Doing the math with arithmetic operators
Getting wise to bitwise operators
Putting it together with string operators
“Hello Operator. Can you give me number 9?”
— The White Stripes
JavaScript operators, expressions, and statements are the basic building blocks of programs. They help you manipulate and change values, perform math, compare two or more values, and much, much more.
In this chapter, you discover how operators, expressions, and statements do their work and how you can best use them to your advantage.
An expression is a piece of code that resolves to a value. Expressions can either assign a value to a variable, or they can simply have a value. For example, both of the following are examples of valid expressions:
1 + 1
a = 1;
Expressions can be short and simple, as illustrated in these examples, or they can be quite complicated.
The pieces of data (1 or a in these examples) in an expression are called operands.
The engines that make expressions do their work are called operators. They operate on data to produce different results. The = and + in the preceding expressions are examples of operators.
A single expression often will contain several operators. Consider the following example:
a + 1 + 2 * 3 / 4;
Depending on the order in which you perform the different calculations, the final value of a
could be any one of the following:
a = 1.75
a = 2.5
a = 2.25
In fact, the actual result of this expression will be 2.5. But how do you know this? Depending on the person doing the math, the division could be done first (3 / 4), the addition could be done first (1 + 2), or the multiplication could be done first (2 * 3).
Clearly, there must be a better way to figure out the answer, and there is! This is where operator precedence comes in. Operator precedence is the order in which operators in an expression are evaluated.
Operators are divided into groups of different levels of precedence, numbered from 0 to 19, as shown in Table 5-1.
Table 5-1 Operator Precedence
Operator |
Use |
Operator Associativity |
Precedence |
Sample Use |
( .. ) |
grouping |
n/a |
0 — highest precedence |
(1 + 3) |
… .. |
operator property access |
left to right |
1 |
myCar.color |
[ .. ] |
array access |
left to right |
1 |
thingsToDo[4] |
new …() |
creates an object (with arguments list) |
n/a |
1 |
new Car ("red") |
function …() |
function call |
left to right |
2 |
function addNumbers (1,2) |
new … |
create an object (without a list) |
right to left |
2 |
new Car |
…++ |
postfix increment |
n/a |
3 |
number++ |
…-- |
postfix decrement |
n/a |
3 |
number-- |
! … |
logical not |
right to left |
4 |
!myVal |
~ … |
bitwise not |
right to left |
4 |
~myVal |
- … |
negation |
right to left |
4 |
-aNumber |
++ … |
prefix increment |
right to left |
4 |
++aNumber |
-- … |
prefix decrement |
right to left |
4 |
--aNumber |
typeof … |
typeof |
right to left |
4 |
typeof myVar |
void … |
void |
right to left |
4 |
void(0) |
delete … |
delete |
right to left |
4 |
delete object.property |
… * … |
multiplication |
left to right |
5 |
result = 3 * 7 |
… / … |
division |
left to right |
5 |
result = 3 / 7 |
… % … |
remainder |
left to right |
5 |
result = 7 % 3 |
… + … |
addition |
left to right |
6 |
result = 3 + 7 |
… - … |
subtraction |
left to right |
6 |
result = 3 - 7 |
… << … |
bitwise left shift |
left to right |
7 |
result = 3 << 7 |
… >> … |
bitwise right shift |
left to right |
7 |
result = 3 >> 7 |
… >>> … |
bitwise unsigned right shift |
left to right |
7 |
result = 3 >>> 7 |
… < … |
less than |
left to right |
8 |
a < b |
… <= … |
less than or equal to |
left to right |
8 |
a <= b |
… > … |
greater than |
left to right |
8 |
a > b |
… >= … |
greater than or equal to |
left to right |
8 |
a >= b |
… in … |
in |
left to right |
8 |
value in values |
… instanceof … |
instanceof |
left to right |
8 |
myCar instanceof car |
… == … |
equality |
left to right |
9 |
3 == “3” // true |
… != … |
inequality |
left to right |
9 |
3 != “3” // false |
… === … |
strict equality |
left to right |
9 |
3 === “3” // false |
… !== … |
strict inequality |
left to right |
9 |
3 !== “3” // true |
… & … |
bitwise and |
left to right |
10 |
result = a & b |
… ^ … |
bitwise xor |
left to right |
11 |
result = a ^ b |
… | … |
bitwise or |
left to right |
12 |
result = a | b |
… && … |
logical and |
left to right |
13 |
a && b |
… || … |
logical or |
left to right |
14 |
a || b |
… ? …:… |
conditional |
right to left |
15 |
a ? 3 : 7 |
… = … |
assignment |
right to left |
16 |
a = 3 |
… += … |
assignment |
right to left |
16 |
a += 3 |
… -= … |
assignment |
right to left |
16 |
a -= 3 |
… *= … |
assignment |
right to left |
16 |
a *= 3 |
… /= … |
assignment |
right to left |
16 |
a /= 3 |
… %= … |
assignment |
right to left |
16 |
a %= 3 |
… <<= … |
assignment |
right to left |
16 |
a <<= 3 |
… >>= … |
assignment |
right to left |
16 |
a >>= 3 |
… >>>= … |
assignment |
right to left |
16 |
a >>>= 3 |
… &= … |
assignment |
right to left |
16 |
a &= 3 |
… ^= … |
assignment |
right to left |
16 |
a ^= 3 |
… |= … |
assignment |
right to left |
16 |
a |= 3 |
yield … |
yield |
right to left |
17 |
yield [expression] |
… , … |
comma / sequence |
left to right |
18 |
a + b, c + d |
When an expression contains two or more operators that have the same precedence, they are evaluated according to their associativity. Associativity determines whether the operators are evaluated from left to right or right to left.
The operator with the highest precedence in an expression is parentheses. In most cases, you can ignore the rules of operator precedence simply by grouping operations into subexpressions using parentheses. For example, the previous multi-operator expression can be fully clarified in the following ways:
a = (1 + 2) * (3 / 4); // result: 2.25
a = (1 + (2 * 3)) / 4; // result: 1.75
a = ((1 + 2) *3) / 4; // result: 2.25
a = 1 + ((2 * 3) / 4); // result: 2.5
Parentheses in expressions force the JavaScript interpreter to evaluate the contents of the parentheses first, from the inner most parentheses to the outermost, before performing the operations outside of the parentheses.
Upon consulting Table 5-1, you’ll see that the actual order of the precedence for the preceding expression is
a = 1 + ((2 * 3) / 4);
This statement makes the actual operator precedence explicit. Multiplication is done first, followed by division, followed by the addition.
JavaScript has a number of types of operators. This section discusses the most commonly used types of operators.
The assignment operator assigns the value of the operand on the right to the operand on the left:
a = 5;
After this expression runs, the variable a
will have a value of 5. You can also chain assignment operators together in order to assign the same value to multiple variables, as in the following example:
a = b = c = 5;
Because the operator’s associativity is right to left (see Table 5-1), 5 will first be assigned to c
, then the value of c
will be assigned to b
, and then the value if b
will be assigned to a
. The result of this expression is that a
, b
, and c
all have a value of 5.
What do you think the end value of a
will be after these expressions are evaluated?
var b = 1;
var a = b += c = 5;
To find out, open up the JavaScript console in Chrome and type each line, followed by return or enter. The result of this statement is that a will be equal to 6
.
Comparison operators test for equality or difference between operands and return a true or false value.
Table 5-2 shows a complete list of the JavaScript comparison operators.
Table 5-2 JavaScript Comparison Operators
Operator |
Description |
Example |
== |
Equality |
3 == “3” // true |
!= |
Inequality |
3 != 3 // false |
=== |
Strict equality |
3 === “3” // false |
!== |
Strict inequality |
3 !== “3” // true |
> |
Greater than |
7 > 1 // true |
>= |
Greater than or equal to |
7 >= 7 // true |
< |
Less than |
7 < 10 // true |
<= |
Less than or equal to |
2 <= 2 // true |
Arithmetic operators perform mathematical operations on operands and return the result. Table 5-3 shows a complete list of arithmetic operators.
Table 5-3 Arithmetic Operators
Operator |
Description |
Example |
+ |
Addition |
a = 1 + 1 |
- |
Subtraction |
a = 10 - 1 |
* |
Multiplication |
a = 2 * 2 |
/ |
Division |
a = 8 / 2 |
% |
Modulus |
a = 5 % 2 |
++ |
Increment |
a = ++b a = b++ a++ |
-- |
Decrement |
a = --b a = b-- a-- |
Listing 5-1 shows arithmetic operators at work.
Listing 5-1: Using Arithmetic Operators
<html>
<head>
<title>arithmetic operators</title>
</head>
<body>
<h1>Wild Birthday Game</h1>
<p>
<ul>
<li>Enter the number 7</li>
<li>Multiply by the month of your birth</li>
<li>Subtract 1</li>
<li>Multiply by 13</li>
<li>Add the day of your birth</li>
<li>Add 3</li>
<li>Multiply by 11</li>
<li>Subtract the month of your birth</li>
<li>Subtract the day of your birth</li>
<li>Divide by 10</li>
<li>Add 11</li>
<li>Divide by 100</li>
</ul>
</p>
<script>
var numberSeven = Number(prompt(‘Enter the number 7’));
var birthMonth = Number(prompt(‘Enter your birth month’));
var calculation = numberSeven * birthMonth;
calculation = calculation - 1;
calculation = calculation * 13;
var birthDay = Number(prompt(‘Enter the day of your birth’));
calculation = calculation + birthDay;
calculation = calculation + 3;
calculation = calculation * 11
calculation = calculation - birthMonth;
calculation = calculation - birthDay;
calculation = calculation / 10;
calculation = calculation + 11;
calculation = calculation / 100;
document.write("Your birthday is " + calculation);
</script>
</body>
</html>
The result of running Listing 5-1 in a browser is shown in Figure 5-1.
The string operator performs operations using two strings. When used with strings, the + operator becomes the concatenation operator. Its purpose is to join together strings. Note that when you’re joining strings with the concatenation operator, no spaces are added. Thus, it’s very common to see statements like the following, where strings containing nothing but a blank space are concatenated between other strings or spaces are added to the end or beginning of strings (before the quotation mark) in order to form a coherent sentence:
var greeting = "Hello, " + firstName + ". I'm" + " " + mood + " to see you.";
Bitwise operators treat operands as signed 32-bit binary representations of numbers in twos complement format. Here’s what that means, starting with the term binary.
Binary numbers are strings of 1s or 0s, with the position of the digit determining the value of a 1 in that position. For example, here’s how to write the number 1 as a 32-bit binary number:
00000000000000000000000000000001
The right most position has a value of 1. Each position to the left of this position has a value of twice the value of the number to its right. So, the following binary number is equal to 5:
00000000000000000000000000000101
Signed integers means that both negative and positive whole numbers can be represented in this form.
The term twos complement means that the opposite of any positive binary number is its negative (and vice versa, of course). So, to change the binary 5 to a binary -5, simply flip all the bits:
11111111111111111111111111111101
Bitwise operators convert numbers to these 32-bit binary numbers and then convert them back to what we would consider normal numbers after the operation has been done.
Table 5-4 lists the JavaScript bitwise operators.
Table 5-4 JavaScript Bitwise Operators
Operator |
Usage |
Description |
Bitwise AND |
a & b |
Returns a 1 in each bit position for which the corresponding bits of both operands are 1s |
Bitwise OR |
a | b |
Returns a 1 in each bit position for which the corresponding bits of either or both operands are 1s |
Bitwise XOR |
a ^ b |
Returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1s |
Bitwise NOT |
~a |
Inverts the bits of its operand |
Left shift |
a << b |
Shifts a in binary representation b (<32) bits to the left shifting in zeros from the right |
Sign-propagating right shift |
a >> b |
Shifts a in binary representation b (<32) bits to the right, discarding bits shifted off |
Zero-fill right shift |
a >>> b |
Shifts a in binary representation b (<32) bits to the right, discarding bits shifted off, and shifting in zeros from the left |
Figure 5-2 shows a demonstration of each of the bitwise operators in the Chrome JavaScript console.
Logical operators evaluate a logical expression for truthiness or falseness. There are three logical operators, shown in Table 5-5.
Table 5-5 Logical Operators
Operator |
Meaning |
Description |
&& |
And |
Returns the first operand if it is |
|| |
Or |
Returns the first operand if it is |
! |
Not |
Takes only one operand. Returns |
var myVar = x||0;
JavaScript’s special operators are a hodge-podge of miscellaneous other symbols and words that perform other and important functions.
The conditional operator (also known as the ternary operator) uses three operands. It evaluates a logical expression and then returns a value based on whether that expression is true or false. The conditional operator is the only operator that requires three operands. For example:
var isItBiggerThanTen = (value > 10) ? "greater than 10" : "not greater than 10";
The comma operator evaluates two operands and returns the value of the second one. It’s most often used to perform multiple assignments or other operations within loops. It can also serve as a shorthand for initializing variables. For example:
var a = 10 , b = 0;
Because the comma has the lowest precedence of the operators, its operands are always evaluated separately.
The delete
operator removes a property from an object or an element from an array.
var animals = ["dog","cat","bird","octopus"];
console.log (animals[3]); // returns "octopus"
delete animals[3];
console.log (animals[3]); // returns "undefined"
The in
operator returns true if the specified value exists in an array or object.
var animals = ["dog","cat","bird","octopus"];
if (3 in animals) {
console.log ("it's in there");
}
In this example, if the animals
array has an element with the index of 3, the string "it's in there"
will print out to the JavaScript console.
The instanceof
operator returns true if the object you specify is the type of object that has been specified.
var myString = new String();
if (myString instanceof String) {
console.log("yup, it's a string!");
}
The new
operator creates an instance of an object. As you can see in Chapter 8, JavaScript has several built-in object types, and you can also define your own. In the following example, Date()
is a built-in JavaScript object, while Pet()
and Flower()
are examples of objects that a programmer could create to serve custom purposes within a program.
var today = new Date();
var bird = new Pet();
var daisy = new Flower();
The this
operator refers to the current object. It’s frequently used for retrieving properties within an object.
Chapter 8 covers the this
operator in much more detail.
The typeof
operator returns a string containing the type of the operand:
var businessName = "Harry's Watch Repair";
console.log typeof businessName; // returns "string"
The void
operator causes an expression in the operand to be evaluated without returning a value. The place where you most often see void used is in HTML documents when a link is needed, but the creator of the link wants to override the default behavior of the link using JavaScript:
<a href="javascript:void(0);">This is a link, but it won't do anything</a>
You can combine assignment operators with the other operators as a shorthand method of assigning the result of an expression to a variable. For example, the following two examples have the same result:
a = a + 10;
a += 10;
Table 5-6 lists all the possible combinations of the assignment operators with other operators.
Table 5-6 Combining the Assignment Operators and Other Operators
Name |
Shorthand |
Standard Operator |
Assignment |
x = y |
x = y |
Addition assignment |
x += y |
x = x + y |
Subtraction assignment |
x -= y |
x = x - y |
Multiplication assignment |
x *= y |
x = x * y |
Division assignment |
x /= y |
x = x / y |
Remainder assignment |
x %= y |
x = x % y |
Left shift assignment |
x <<= y |
x = x << y |
Right shift assignment |
x >>= y |
x = x >> y |
Unassigned right shift assignment |
x >>>= y |
x = x <<< y |
Bitwise AND assignment |
x &= y |
x = x & y |
Bitwise XOR assignment |
x ^= y |
x = x ^ y |
Bitwise OR assignment |
x |= y |
x = x | y |