Chapter 3
IN THIS CHAPTER
Understanding what expressions are
Figuring out numeric expressions
Tying up string expressions
Getting the hang of comparison expressions
Learning about logical expressions
It’s not at all important to get it right the first time. It’s vitally important to get it right the last time.
— DAVID THOMAS
The JavaScript variables described in the previous chapter can’t do all that much by themselves. They don’t become useful members of your web code community until you give them something productive to do. For example, you can assign values to them, use them to assign values to other variables, use them in calculations, and so on.
This productive side of variables in particular, and JavaScript-based web code in general, is brought to you by a JavaScript feature known as the expression. This chapter takes you through everything you need to know about expressions. You discover some expression basics and then you explore a number of techniques for building powerful expressions using numbers, strings, and Boolean values.
To be as vague as I can be, an expression is a collection of symbols, words, and numbers that performs a calculation and produces a result. That’s a nebulous definition, I know, so I’ll make it more concrete.
When your check arrives after a restaurant meal, one of the first things you probably do is take out your smartphone and use the calculator to figure out the tip amount. The service and food were good, so you’re thinking 20 percent is appropriate. With phone in hand, you tap in the bill total, tap the multiplication button, tap 20%, and then tap Equals. Voila! The tip amount appears on the screen and you’re good to go.
A JavaScript expression is something like this kind of procedure because it takes one or more inputs, such as a bill total and a tip percentage, and combines them in some way — for example, by using multiplication. In expression lingo, the inputs are called operands, and they’re combined by using special symbols called operators.
*
operator represents multiplication, and the +
operator represents addition. I discuss the various JavaScript operators throughout this chapter.For example, here's an expression that calculates a tip amount and assigns the result to a variable:
tipAmount = billTotal * tipPercentage;
The expression is everything to the right of the equals sign (=
). Here, billTotal
and tipPercentage
are the operands, and the multiplication sign (*
) is the operator.
Calculating a tip amount on a restaurant bill is a mathematical calculation, so you may be thinking that JavaScript expressions are going to be mostly mathematical. If I was standing in front of you and I happened to have a box of gold stars on me, then I’d certainly give you one because, yes, math-based expressions are probably the most common type you’ll come across.
This type of calculation is called a numeric expression, and it combines numeric operands and arithmetic operators to produce a numeric result. This section discusses all the JavaScript arithmetic operators and shows you how best to use them to build useful and handy numeric expressions.
JavaScript’s basic arithmetic operators are more or less the same as those found in your smartphone’s calculator app or on the numeric keypad of your computer’s keyboard, plus a couple of extra operators for more advanced work. Table 3-1 lists the basic arithmetic operators you can use in your JavaScript expressions. (In subsequent sections, I discuss each one in more detail.)
TABLE 3-1 The JavaScript Arithmetic Operators
Operator |
Name |
Example |
Result |
|
Addition |
|
|
|
Increment |
|
|
|
Subtraction |
|
|
|
Negation |
|
|
|
Decrement |
|
|
|
Multiplication |
|
|
|
Division |
|
|
|
Modulus |
|
|
JavaScript also comes with a few extra operators that combine some of the arithmetic operators and the assignment operator, which is the humble equal sign (=
) that assigns a value to a variable. Table 3-2 lists these so-called arithmetic assignment operators.
TABLE 3-2 The JavaScript Arithmetic Assignment Operators
Operator |
Example |
Equivalent |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
You use the addition operator (+
) to calculate the sum of two operands. The operands are usually of the numeric data type, which means they can be numeric literals, variables that store numeric values, or methods or functions that return numeric values. Here's an example:
widthMax = widthContent + widthSidebar + 100;
You could use such an expression in a web app when you need to know the maximum width to assign the app’s container. In this case, you take the width of the app’s content (represented by the widthContent
variable), add the width of the app’s sidebar (the widthSidebar
variable), and then add the literal value 100
(which may be a value in pixels).
One of the most common programming operations involves adding 1 to an existing value, such as a variable. This operation is called incrementing the value, and the standard way to write such a statement is as follows:
someVariable = someVariable + 1;
However, JavaScript offers a much more compact alternative that uses the increment operator (++
):
++someVariable;
The subtraction operator (-
) subtracts the numeric value to the right of the operator from the numeric value to the left of the operator. For example, consider the following statements:
var targetYear = 2020;
var birthYear = 1985;
var yearsDifference = targetYear – birthyear;
The third statement subtracts 1985 from 2020 and the result — 35 — is stored in the yearsDifference
variable.
The negation operator (-
) is the same symbol, but it works in a totally different way. You use it as a kind of prefix by appending it to the front of an operand. The result is a new value that has the opposite sign of the original value. In other words, applying the negation operator to an operand is exactly the same as multiplying the operand by -1. This means the following two statements are identical:
negatedValue = -originalValue;
negatedValue = originalValue * -1;
Another common programming operation is subtracting 1 from an existing variable or other operand. This operation is called decrementing the value, and the usual way to go about this is with a statement like this one:
thisVariable = thisVariable - 1;
However (you just knew there was going to be a however), JavaScript offers a much more svelte alternative that takes advantage of the decrement operator (--
):
--thisVariable;
The multiplication operator (*
) multiplies two operands together. Here's an example:
var totalColumns = 8;
var columnWidth = 100;
var totalWidth = totalColumns * columnWidth;
You might use this code when you want to calculate the width taken up by a web page layout that uses multiple columns. This code assigns literal numeric values to the variables totalColumns
and columnWidth
. It then uses a numeric expression to multiply these two values together and assign the result to the totalWidth
variable.
The division operator (/
) divides one numeric value by another. You can show off at parties by remembering that the number to the left of the slash (/
) is called the dividend, and the number to the right of the /
is called the divisor:
dividend / divisor
Here's an example:
var contentWidth = 600;
var windowWidth = 1200;
var contentRatio = contentWidth / windowWidth;
You can use this code to calculate the portion of the browser’s window width that the page content is currently using. In this code, the variables contentWidth
and windowWidth
are assigned literal numeric values, and then a numeric expression divides the first of the values by the second, the result of which is stored in the contentRatio
variable.
The modulus operator (%
) divides one number by another and then returns the remainder as the result:
dividend % divisor
For example, the following code stores the value 1
in the variable named myModulus
because 5 (the myDivisor
value) divides into 16 (the myDividend
value) three times and leaves a remainder of 1:
var myDividend = 16;
var myDivisor = 5;
var myModulus = myDividend % myDivisor;
On a more practical level, suppose that you're trying to come up with a web page color scheme, and you want to use two colors that are complements of each other. Complementary means that the two hues are on the opposite side of the color wheel, so one way to calculate the second color is by adding 180 to the first color’s hue value. That approach works when the hue of the first color is between 0 and 179, which give second color hue values between 180 and 359. However, an initial hue of 180, 181, and so on produces a second hue of 360, 361, and so on, which are illegal values. You can work around that issue by using a modulus expression like this:
complementaryColor = (originalColor + 180) % 360;
This statement adds 180 to the original color, but then uses % 360
to return the remainder when divided by 360 to avoid illegal values.
Your web coding scripts will often update the value of a variable by adding to it the value of some other operand. Here’s an example:
totalInterestPaid = totalInterestPaid + monthlyInterestPaid
Coders are an efficiency-loving bunch, so the fact that the totalInterestPaid
variable appears twice in that statement is like chewing tin foil to your average programmer. The JavaScript brain trust hate that kind of thing, too, so they came up with the addition assignment operator (+=
):
totalInterestPaid += monthlyInterestPaid
Yep, this statement does exactly the same thing as the first one, but it does it with 19 fewer characters. Sweet!
If you need to subtract one operand from another, again you can do it the old-fashioned way:
housePrincipleOwing = housePrincipleOwing - monthlyPrincipalPaid
To avoid other coders laughing behind your back at your inefficiency, use the subtraction assignment operator (-=
):
housePrincipleOwing -= monthlyPrincipalPaid
A string expression is one where at least one of the operands is a string, and the result of the expression is another string. String expressions are straightforward in the sense that there is only one operator to deal with: concatenation (+
). You use this operator to combine (or concatenate) strings within an expression. For example, the expression "Java" + "Script"
returns the string "JavaScript"
. Note, however, that you can also use strings with the comparison operators discussed in the next section.
It's unfortunate that the concatenation operator is identical to the addition operator because this similarity can lead to some confusion. For example, the expression 2 + 2
returns the numeric value 4
because the operands are numeric. However, the expression "2" + "2"
returns the string value 22
because the two operands are strings.
To further complicate matters, JavaScript will often convert numbers into strings depending on the context:
222
:
"2" + 2 + 2
42
because the result of 2 + 2
is 4
, which is then concatenated as a string to "2"
:
2 + 2 + "2"
As an example of how this conversion can be a problem, consider the script in the following code.
var preTipTotal = 10.00;
var tipAmount = preTipTotal * 0.15;
var message1 = "Your tip is ";
var message2 = "
Your total bill is ";
alert(message1 + tipAmount + message2 + preTipTotal + tipAmount);
The preTipTotal
variable stores a total for a restaurant bill, and the tipAmount
variable stores 15 percent of the total. The variables message1
and message2
are initialized with strings, and then an alert box is displayed with the results. In particular, the expression preTipTotal + tipAmount
is included in the alert()
method to display the total bill. However, as you can see in Figure 3-1, the “total” displayed is actually 101.5
instead of 11.5
(10 plus 1.5 for the tip).
What happened here is that because the first part of the expression in the alert()
method was a string, JavaScript converted the preTipTotal
and tipAmount
values to strings and concatenated them instead of adding them.
To fix this, you could perform the addition in a separate statement and then use only this sum in the alert()
expression. The following code demonstrates this approach:
var preTipTotal = 10.00;
var tipAmount = preTipTotal * 0.15;
var totalBill = preTipTotal + tipAmount;
var message1 = "Your tip is ";
var message2 = "
Your total bill is ";
alert(message1 + tipAmount + message2 + totalBill);
A new variable named totalBill
is declared and is used to store the preTipTotal + tipAmount
sum. totalBill
is then used to display the sum in the alert()
expression, which, as you can see in Figure 3-2, now displays the correct answer.
You use comparison expressions to compare the values of two or more numbers, strings, variables, properties, or function results. If the expression is true, the expression result is set to the Boolean value true
; if the expression is false, the expression result is set to the Boolean value false
. You'll use comparisons with alarming frequency in your JavaScript code, so it’s important to understand what they are and how you use them.
Table 3-3 summarizes JavaScript’s comparison operators.
TABLE 3-3 The JavaScript Comparison Operators
Operator |
Name |
Example |
Result |
|
Equal |
|
|
|
Not equal |
|
|
|
Greater than |
|
|
|
Less than |
|
|
|
Greater than or equal |
|
|
|
Less than or equal |
|
|
|
Identity |
|
|
|
Non-identity |
|
|
You use the equal operator (==
) to compare the values of two operands. If both have the same value, then the comparison returns true
; if the operands have different values, the comparison returns false
.
For example, in the following statements the variables booksRead
and weeksPassed
contain the same value, so the expression booksRead == weeksPassed
returns true
:
var booksRead = 48;
var weeksPassed = 48;
var bookAWeek = booksRead == weeksPassed;
You also use the not equal operator (!=
) to compare the values of two operands, but in the opposite way. That is, if the operands have different values, the comparison returns true
; if both operands have the same value, the comparison returns false
.
In the following statements, for example, the variables currentFontSize
and defaultFontSize
contain different values, so the expression currentFontSize!= defaultFontSize
returns true
:
var currentFontSize = 19;
var defaultFontSize = 16;
var weirdoFontSize = currentFontSize != defaultFontSize;
You use the greater than operator (>
) to compare two operands to see if the operand to the left of >
has a greater value than the operand to the right of >
. If it does, then the expression returns true
; otherwise, it returns false
.
In the statements below, the value of the contentWidth
variable is more than that of the windowWidth
variable, so the expression contentWidth > windowWidth
returns true
:
var contentWidth = 1000;
var windowWidth = 800;
var tooBig = contentWidth > windowWidth;
You use the less than operator (<
) to compare two operands to see if the operand to the left of >
has a lesser value than the operand to the right of >
. If it does, then the expression returns true
; otherwise, it returns false
.
For example, in the statements that follow, the values of the kumquatsInStock
and kumquatsSold
variables are the same, so the expression kumquatsInStock < kumquatsSold
returns false
:
var kumquatsInStock = 3;
var kumquatsSold = 3;
var backordered = kumquatsInStock < kumquatsSold;
You use the greater than or equal operator (>=
) to compare two operands to see if the operand to the left of >=
has a greater value than or an equal value to the operand to the right of >=
. If either or both of those comparisons get a thumbs up, then the expression returns true
; otherwise, it returns false
.
In the following statements, for example, the value of the score
variable is more than that of the prize1Minimum
variable and is equal to that of the prize2Minimum
variable. Therefore, both the expressions score >= prize1Minimum
and score >= prize2Minimum
return true
:
var score = 90;
var prize1Minimum = 80;
var prize2Minimum = 90;
var getsPrize1 = score >= prize1Minimum;
var getsPrize2 = score >= prize2Minimum;
You use the less than or equal operator (<=
) to compare two operands to see if the operand to the left of <=
has a lesser value than or an equal value to the operand to the right of <=
. If either or both of those comparisons get a nod of approval, then the expression returns true
; otherwise, it returns false
.
For example, in the following statements, the value of the defects
variable is less than that of the defectsMaximumA
variable and is equal to that of the defectsMaximumB
variable. Therefore, both the expressions defects <= defectsMaximumA
and defects <= defectsMaximumB
return true
:
var defects = 5
var defectsMaximumA = 10
var defectsMaximumB = 5
var getsBonus = defects <= defectsMaximumA
var getsRaise = defects <= defectsMaximumB
In the previous examples, I used only numbers to demonstrate the various comparison operators. However, you can also use strings and Boolean values. These comparisons are straightforward if your expressions include only operands of the same data type; that is, if you compare two strings or two Booleans. (Although see my discussion of using strings in comparison expressions a bit later in this chapter.)
"5"
gets converted to the number 5, so the comparison value1 == value2
returns true
:
var value1 = "5"
var value2 = 5
var result = value1 == value2
If the string can't be converted to a number, then the comparison always returns false
.
If one operand is a Boolean and the other is a number, JavaScript converts the Boolean to a number as follows:
true
— This value is converted to 1
.false
— This value is converted to 0
.For example, in the following statements, the Boolean true
gets converted to the number 1, so the comparison value1 == value2
returns true
:
var value1 = true
var value2 = 1
var result = value1 == value2
false
is converted to the number 0 and the string "0"
is converted to the number 0, so the comparison value1 == value2
returns true
:
var value1 = false
var value2 = "0"
var result = value1 == value2
If the string can't be converted to a number, then the comparison always returns false
.
The identity operator (===
) checks whether two operands are identical, which means it checks not only that the operands' values are equal, but also that the operands are of the same data type. (Which is why the identity operator is also sometimes called the strict equality operator.)
For example, in the following statements, variable albumName
contains a string and variable albumReleaseDate
contains a number. These values are of different data types, so the expression albumName === albumReleaseDate
returns false
:
var albumName = "1984";
var albumReleaseDate = 1984;
var result = albumName === albumReleaseDate;
By comparison, if instead you used the equal operator (==
), which doesn't check the operand data types, the expression albumName == albumReleaseDate
would return true
.
The non-identity operator (!==
) performs the opposite function, sort of. That is, it checks to see not only if the values of two operands are different, but it also checks to see whether the operand are of different data types. (Which is why the non-identity operator is also sometimes called the strict inequality operator.)
In the statements below, variable hasBugs
contains the Boolean value true
and variable totalBugs
contains a number. These values are of different data types, so the expression hasBugs !== totalBugs
returns true
:
var hasBugs = true;
var totalBugs = 1;
var result = hasBugs !== totalBugs;
Comparison expressions involving only numbers hold few surprises, but comparisons involving only strings can sometimes raise an eyebrow or two. The comparison is based on alphabetical order, as you might expect, so “A” comes before “B” and “a” comes before “b.” Ah, but this isn't your father’s alphabetical order. In JavaScript’s world, all the uppercase letters come before all the lowercase letters, which means that, for example, “B” comes before “a,” so the following expression would return false
:
"a" < "B"
Another thing to keep in mind is that most string comparisons involve multiple-letter operands. In these situations, JavaScript compares each string letter-by-letter. For example, consider the following expression:
"Smith" < "Smyth"
The first two letters in each string are the same, but the third letters are different. The internal value of the i
in Smith
is less than the internal value of the y
in Smyth
, so the comparison above would return true
. (Notice, too, that after a point of difference is found, JavaScript ignores the rest of the letters in each string.)
Also, a space is a legitimate character for comparison purposes, and its internal value comes before all other letters and symbols. In particular, if you compare two strings of different lengths, JavaScript will pad the shorter string with spaces so that it's the same length as the longer string. Therefore, the following two expressions are equivalent:
"Marg" > "Margaret"
"Marg " > "Margaret"
The second statement returns false
because the fifth “letter” of the left operand is a space, whereas the fifth letter of "Margaret"
is a
.
expression ? result_if_true : result_if_false
The expression
is a comparison expression that results in a true
or false
value. In fact, you can use any variable, function result, or property that has a true
or false
Boolean value. The result_if_true
is the value that the expression returns if the expression
evaluates to true
; the result_if_false
is the value that the expression returns if the expression
evaluates to false
.
0
(the number zero)""
(the empty string)null
undefined
(which is, say, the “value” of an uninitialized variable)Everything else is the equivalent of true
.
Here's a simple example:
var screenWidth = 768;
var maxPortableWidth = 1024;
var screenType = screenWidth > maxPortableWidth ? "Desktop" : "Portable";
The variable screenWidth
is initialized to 768
, the variable maxPortableWidth
is initialized to 1024
, and the variable screenType
stores the value returned by the conditional expression. For the latter, screenWidth > maxPortableWidth
is the comparison expression, "Desktop!"
is the string that is returned given a true
result, and "Portable!"
is the string that is returned given a false
result. Since screenWidth
is less than maxPortableWidth
, the comparison will be false
, so "Portable!"
will be the result.
You use logical expressions to combine or manipulate Boolean values, particularly comparison expressions. For example, if your code needs to test whether two different comparison expressions are both true
before proceeding, you can do that with a logical expression.
Table 3-4 lists JavaScript's logical operators.
TABLE 3-4 The JavaScript Logical Operators
Operator |
Name |
General Syntax |
Returned Value |
|
AND |
|
|
|
OR |
|
|
|
NOT |
|
|
You use the AND operator (&&
) when you want to test two Boolean operands to see if they're both true
. For example, consider the following statements:
var finishedDinner = true;
var clearedTable = true;
var getsDessert = finishedDinner && clearedTable;
Since both finishedDinner
and clearedTable
are true
, the logical expression finishedDinner && clearedTable
evaluates to true
.
On the other hand, consider these statements:
var haveWallet = true;
var haveKeys = false;
var canGoOut = haveWallet && haveKeys;
In this example, since haveKeys
is false
, the logical expression haveWallet && haveKeys
evaluates to false
. The logical expression would also return false
if just haveWallet
was false
or if both haveWallet
and haveKeys
were false
.
Table 3-5 lists the various operands you can enter and the results they generate (this is called a truth table).
TABLE 3-5 Truth Table for the AND (&&
) Operator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
You use the OR (||
) operator when you want to test two Boolean operands to see if at least one of them is true
. For example, consider the following statements:
var hasFever = true;
var hasCough = false;
var missSchool = hasFever || hasCough;
Since hasFever
is true
, the logical expression hasFever || hasCough
evaluates to true
since only one of the operands needs to be true
. You get the same result if only hasCough
is true
or if both operands are true
.
On the other hand, consider these statements:
var salesOverBudget = false;
var expensesUnderBudget = false;
var getsBonus = salesOverBudget || expensesUnderBudget;
In this example, since both salesOverBudget
and expensesUnderBudget
are false
, the logical expression salesOverBudget || expensesUnderBudget
evaluates to false
.
Table 3-6 displays the truth table for the various operands you can enter.
TABLE 3-6 Truth Table for the OR (||
) Operator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The NOT (!
) operator is the logical equivalent of the negation operator (-
) I cover earlier in this chapter. In this case, NOT returns the opposite Boolean value of an operand. For example, consider the following statements:
var dataLoaded = false;
var waitingForData = !dataLoaded;
dataLoaded
is false
, so !dataLoaded
evaluates to true
.
Table 3-7 displays the truth table for the various operands you can enter.
TABLE 3-7 Truth Table for the NOT (!
) Operator
|
|
true |
false |
false |
true |
Let's begin with an AND expression:
false
or is equivalent to false
, return that value and stop; otherwise, continue with Step 3.true
or is equivalent to true
, evaluate the operand to the right of the AND operator.This is quirky behavior, indeed, and there are two crucial concepts you need to bear in mind:
false
or its equivalent, the right operand is never evaluated.true
or false
; instead, it might return a value that's equivalent to true
or false
.To try these concepts out, use the following code:
var v1 = true;
var v2 = 10;
var v3 = "testing";
var v4 = false;
var v5 = 0;
var v6 = "";
var leftOperand =
eval(prompt("Enter the left operand (a value or expression):", true));
var rightOperand =
eval(prompt("Enter the right operand (a value or expression):", true));
var result = leftOperand && rightOperand;
alert(result);
The script begins by declaring and initializing six variables. The first three (v1
, v2
, and v3
) are given values equivalent to true
and the last three (v4
, v5
, and v6
) are given values equivalent to false
. The script then prompts for a left operand and a right operand, which are then entered into an AND expression. The key here is that you can enter any value for each operand, or you can use the v1
through v6
variables to enter a comparison expression, such as v2 > v5
. The use of eval()
on the prompt()
result ensures that JavaScript uses the expressions as they're entered.
Table 3-8 lists some sample inputs and the results they generate.
TABLE 3-8 Some Sample Results for the Previous Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Like the AND operator, the logic of how JavaScript evaluates an OR expression is strange and needs to be understood, particularly if you'll be using operands that are true
or false
equivalents:
true
or is equivalent to true
, return that value and stop; otherwise, continue with Step 3.false
or is equivalent to false
, evaluate the operand to the right of the AND operator.Your JavaScript code will often use expressions that are blissfully simple: just one or two operands and a single operator. But, alas, “often” here doesn't mean “mostly,” because many expressions you use will have a number of values and operators. In these more complex expressions, the order in which the calculations are performed becomes crucial. For example, consider the expression 3+5*2
. If you calculate from left to right, the answer you get is 16
(3+5
equals 8
, and 8*2
equals 16
). However, if you perform the multiplication first and then the addition, the result is 13
(5*2
equals 10
, and 3+10
equals 13
). In other words, a single expression can produce multiple answers depending on the order in which you perform the calculations.
To control this ordering problem, JavaScript evaluates an expression according to a predefined order of precedence. This order of precedence lets JavaScript calculate an expression unambiguously by determining which part of the expression it calculates first, which part second, and so on.
The order of precedence that JavaScript uses is determined by the various expression operators covered so far in this chapter. Table 3-9 summarizes the complete order of precedence used by JavaScript.
TABLE 3-9 The JavaScript Order of Precedence for Operators
Operator |
Operation |
Order of Precedence |
Order of Evaluation |
|
Increment |
First |
R -> L |
|
Decrement |
First |
R -> L |
|
Negation |
First |
R -> L |
|
NOT |
First |
R -> L |
|
Multiplication, division, modulus |
Second |
L -> R |
|
Addition, subtraction |
Third |
L -> R |
|
Concatenation |
Third |
L -> R |
|
Less than, less than, or equal |
Fourth |
L -> R |
|
Greater than, greater than, or equal |
Fourth |
L -> R |
|
Equal |
Fifth |
L -> R |
|
Not equal |
Fifth |
L -> R |
|
Identity |
Fifth |
L -> R |
|
Non-identity |
Fifth |
L -> R |
|
AND |
Sixth |
L -> R |
|
OR |
Sixth |
L -> R |
|
Ternary |
Seventh |
R -> L |
|
Assignment |
Eighth |
R -> L |
|
Arithmetic assignment |
Eighth |
R -> L |
For example, Table 3-9 tells you that JavaScript performs multiplication before addition. Therefore, the correct answer for the expression =3+5*2
(just discussed) is 13
.
Notice, as well, that some operators in Table 3-9 have the same order of precedence (for example, multiplication and division). Having the same precedence means that the order in which JavaScript evaluates these operators doesn't matter. For example, consider the expression 5*10/2
. If you perform the multiplication first, the answer you get is 25
(5*10
equals 50
, and 50/2
equals 25
). If you perform the division first, you also get an answer of 25
(10/2
equals 5
, and 5*5
equals 25
).
However, JavaScript does have a predefined order for these kinds of expressions, which is what the Order of Evaluation column tells you. A value of L -> R means that operations with the same order of precedence are evaluated from left-to-right; R -> L means the operations are evaluated from right-to-left.
Sometimes you want to take control of the situation and override the order of precedence. That might seem like a decidedly odd thing to do, so perhaps an example is in order. As you probably know, you calculate the total cost of a retail item by multiplying the retail price by the tax rate, and then adding that result to the retail price:
Total Price = Retail Price + Retail Price * Tax Rate
However, what if you want to reverse this calculation? That is, suppose you know the final price of an item and, given the tax rate, you want to know the original (that is, pre-tax) price. Applying a bit of algebra to the preceding equation, it turns out that you can calculate the original price by dividing the total price by 1 plus the tax rate. So if the total price is $11.00 and the tax rate is 10%, then you divide 11 by 1.1 and get an answer of $10.00.
Okay, now I'll convert this calculation to JavaScript code. A first pass at the new equation might look something like this:
retailPrice = totalPrice / 1 + taxRate;
The following code implements this formula and Figure 3-3 shows the result:
var totalPrice = 11.00;
var taxRate = .1;
var retailPrice = totalPrice / 1 + taxRate;
alert("The pre-tax price is " + retailPrice);
As you can see, the result is incorrect. What happened? Well, according to the rules of precedence, JavaScript performs division before addition, so the totalPrice
value first is divided by 1 and then is added to the taxRate
value, which isn't the correct order.
To get the correct answer, you have to override the order of precedence so that the addition 1 + taxRate
is performed first. You override precedence by surrounding that part of the expression with parentheses, as shown in the following code. Using this revised script, you get the correct answer, as shown in Figure 3-4.
var totalPrice = 11.00;
var taxRate = .1;
var retailPrice = totalPrice / (1 + taxRate);
alert("The pre-tax price is " + retailPrice);
In general, you can use parentheses to control the order that JavaScript uses to calculate expressions. Terms inside parentheses are always calculated first; terms outside parentheses are calculated sequentially (according to the order of precedence). To gain even more control over your expressions, you can place parentheses inside one another; this is called nesting parentheses, and JavaScript always evaluates the innermost set of parentheses first.
Using parentheses to determine the order of calculations allows you to gain full control over JavaScript expressions. This way, you can make sure that the answer given by an expression is the one you want.
18.218.196.182