Chapter 3

Building Expressions

IN THIS CHAPTER

check Understanding what expressions are

check Figuring out numeric expressions

check Tying up string expressions

check Getting the hang of comparison expressions

check 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.

Understanding Expression Structure

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.

  • Operand: An input value for an expression. It is, in other words, the raw data that the expression manipulates to produce its result. It could be a number, a string, a variable, a function result (see Book 3, Chapter 5), or an object property (see Book 3, Chapter 8).
  • Operator: A symbol that represents a particular action performed on one or more operands. For example, the * 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.

technicalstuff Expression results always have a particular data type — numeric, string, or Boolean. So when you're working with expressions, always keep in mind what type of result you need and then choose the appropriate operands and operators accordingly.

remember Another analogy I like to use for operands and operators is a grammatical one — that is, if you consider an expression to be a sentence, then the operands are the nouns (the things) of the sentence, and the operators are the verbs (the actions) of the sentence.

Building Numeric Expressions

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.

A quick look at the arithmetic operators

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

10 + 4

14

++

Increment

10++

11

-

Subtraction

10 - 4

6

-

Negation

-10

-10

--

Decrement

10--

9

*

Multiplication

10 * 4

40

/

Division

10 / 4

2.5

%

Modulus

10 % 4

2

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

+=

x += y

x = x + y

-=

x -= y

x = x - y

*=

x *= y

x = x * y

/=

x /= y

x = x / y

^=

x ^= y

x = x ^ y

%=

x %= y

x = x % y

Using the addition (+) operator

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).

Using the increment (++) operator

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;

Using the subtraction and negation (-) operators

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;

Using the decrement (--) operator

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;

Using the multiplication (*) operator

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.

Using the division (/) operator

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.

warning Whenever you use the division operator, you must guard against cases where the divisor is 0. If that happens, your script will produce an Infinity result, which is almost certain to wreak havoc on your calculations. Before performing any division, your script should use an if() statement (see Book 3, Chapter 4) to check whether the divisor is 0 and, if it is, to cancel the division or perform some kind of work-around.

Using the modulus (%) operator

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.

Using the arithmetic assignment operators

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

remember Like the increment and decrement operators, the arithmetic assignment operators are designed to save wear-and-tear on your typing fingers and to reduce the size of your scripts, particularly if you use long variable names.

Building String Expressions

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:

  • If the first operand in an expression is a string, JavaScript converts any number in the expression to a string. For example, the following expression returns the string 222:

    "2" + 2 + 2

  • If the first two or more operands in an expression are numbers and the rest of the expression contains a string, JavaScript handles the numeric part of the expression first and then converts the result into a string. For example, the following expression returns the string 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).

image

FIGURE 3-1: When the result is displayed, the preTipTotal and tipAmount values are concatenated instead of added.

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.

image

FIGURE 3-2: Calculating preTipTotal and tipAmount separately fixes the problem.

Building Comparison Expressions

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.

The comparison operators

Table 3-3 summarizes JavaScript’s comparison operators.

TABLE 3-3 The JavaScript Comparison Operators

Operator

Name

Example

Result

==

Equal

10 == 4

false

!=

Not equal

10 != 4

true

>

Greater than

10 > 4

true

<

Less than

10 < 4

false

>=

Greater than or equal

10 >= 4

true

<=

Less than or equal

10 <= 4

false

===

Identity

"10" === 10

false

!==

Non-identity

"10" !== 10

true

Using the equal (==) operator

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;

warning One of the most common mistakes made by beginning and experienced JavaScript programmers alike is to use = instead of == in a comparison expression. If your script isn't working properly or is generating errors, one of the first things you should check is that your equal operator has two equal signs.

Using the not equal (!=) operator

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;

Using the greater than (>) operator

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;

Using the less than (<) operator

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;

Using the greater than or equal (>=) operator

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;

Using the less than or equal (<=) operator

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

The comparison operators and data conversion

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.)

technicalstuff Things become less straightforward if you mix data types within a single comparison expression. In this case, you need to remember that JavaScript always attempts to convert each operand into a number before running the comparison. Here's how it works:

  • If one operand is a string and the other is a number, JavaScript attempts to convert the string into a number. For example, in the following statements the string "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

  • If one operand is a Boolean and the other is a string, JavaScript converts the Boolean to a number as in the previous item, and it attempts to convert the string into a number. For example, in the following statements, the Boolean 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.

Using the identity (===) operator

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.

remember So when should you use equal (==) and when should you use identity (===)? Many pro JavaScript coders ignore this question entirely and just use the identity operator all the time. You should, too.

Using the non-identity (!==) operator

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;

Using strings in comparison expressions

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.

Using the ternary (?:) operator

technicalstuff Knowing the comparison operators also enables you to use one of my favorite expression tools, a complex but oh-so-handy item called the ternary operator (?:). Here's the basic syntax for using the ternary operator in an expression:

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.

tip In JavaScript, by definition, the following values are the equivalent of 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.

Building Logical Expressions

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.

The logical operators

Table 3-4 lists JavaScript's logical operators.

TABLE 3-4 The JavaScript Logical Operators

Operator

Name

General Syntax

Returned Value

&&

AND

expr1 && expr2

true if both expr1 and expr2 are true; false otherwise.

||

OR

expr1 || expr2

true if one or both of expr1 and expr2 are true; false otherwise.

!

NOT

!expr

true if expr is false; false if expr is true.

Using the AND (&&) operator

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

left_operand

right_operand

left_operand && right_operand

true

true

true

true

false

false

false

true

false

false

false

false

Using the OR (||) 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

left_operand

right_operand

left_operand || right_operand

true

true

true

true

false

true

false

true

true

false

false

false

Using the NOT (!) 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

Operand

!Operand

true

false

false

true

Advanced notes on the && and || operators

technicalstuff I mention earlier that JavaScript defines various values that are the equivalent of false — including 0 and "" — and that all other values are the equivalent of true. These equivalences means that you can use both the AND operator and the OR operator with non-Boolean values. However, if you plan on using non-Booleans, then you need to be aware of exactly how JavaScript evaluates these expressions.

Let's begin with an AND expression:

  1. Evaluate the operand to the left of the AND operator.
  2. If the left operand’s value is false or is equivalent to false, return that value and stop; otherwise, continue with Step 3.
  3. If the left operand's value is true or is equivalent to true, evaluate the operand to the right of the AND operator.
  4. Return the value of the right operand.

This is quirky behavior, indeed, and there are two crucial concepts you need to bear in mind:

  • If the left operand evaluates to false or its equivalent, the right operand is never evaluated.
  • The logical expression returns the result of either the left or right operand, which means the expression might not return 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

left_operand

right_operand

left_operand && right_operand

true

true

true

true

false

false

5

10

10

false

"Yo"

false

v2

v5

0

true

v3

testing

v5

v4

0

v2 > v5

v5 == v4

true

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:

  1. Evaluate the operand to the left of the OR operator.
  2. If the left operand's value is true or is equivalent to true, return that value and stop; otherwise, continue with Step 3.
  3. If the left operand's value is false or is equivalent to false, evaluate the operand to the right of the AND operator.
  4. Return the value of the right operand.

Understanding Operator Precedence

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

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

+=, -=, and so on.

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.

Controlling the order of precedence

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);

image

FIGURE 3-3: The result of our first stab at calculating the pre-tax cost of an item.

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);

image

FIGURE 3-4: The revised script calculates the pre-tax cost correctly.

warning One of the most common mistakes when using parentheses in expressions is to forget to close a parenthetic term with a right parenthesis. To make sure you’ve closed each parenthetic term, count all the left parentheses and count all the right parentheses. If these totals don’t match, you know you’ve left out a parenthesis.

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.

..................Content has been hidden....................

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