Chapter 5

JavaScript Operators

Key Skills & Concepts

   Understanding the Operator Types

   Understanding Arithmetic (Mathematical) Operators

   Understanding Assignment Operators

   Understanding Comparison Operators

   Understanding Logical Operators

   Understanding Order of Operations

Operators do much of the work in scripts. In the previous chapters, you have seen examples of the use of the assignment (=) and addition (+) operators. JavaScript offers many other types of operators to perform various operations.

This chapter begins by giving you an introduction to the different types of JavaScript operators. Then, you will learn about each operator and its use in scripts. Finally, you will learn about the order of precedence for operators, which determines which operations are performed before others.

Understanding the Operator Types

An operator is a symbol or keyword in JavaScript that performs some sort of calculation, comparison, or assignment on one or more values. In some cases, an operator provides a shortcut to shorten the code so that you have less to type.

Common calculations include finding the sum of two numbers, combining two strings, or dividing two numbers. Some common comparisons might be to find out if two values are equal or to see if one value is greater than the other. A shortcut assignment operator might be used to assign a new value to a variable so that the variable name does not need to be typed twice.

JavaScript uses several different types of operators:

   Arithmetic   These operators are most often used to perform mathematical calculations on two values. The arithmetic operators will probably be the most familiar to you. They use symbols such as +, –, and *.

   Assignment   These operators are used to assign new values to variables. As you learned in Chapter 3, one of the assignment operators is the symbol =.

   Comparison   These operators are used to compare two values, two variables, or perhaps two longer statements. They use symbols such as > (for “is greater than”) and < (for “is less than”).

   Logical   These operators are used to compare two conditional statements (or to operate on one statement) to determine if the result is true and to proceed accordingly. They use symbols such as && (returns true if the statements on both sides of the operator are true) and || (returns true if a statement on either side of the operator is true).

   Bitwise   These are logical operators that work at the bit level (ones and zeros). They use symbols like << (for left-shifting bits) and >> (for right-shifting bits).

   Special   These are operators that perform other special functions of their own.

In this chapter, you will learn about each of these types of operators. This will be a general overview of the function of each type of operator, so that you will better know the purpose of all the operator types when you put them to use later. To begin, you’ll look at the arithmetic operators in JavaScript.

Understanding Arithmetic Operators

For a mathematical calculation, you use an arithmetic operator. The values that you use can be any sort of values you like. For instance, you could use two variables, two numbers, or a variable and a number. A few of these operators are able to perform a task on a single value.

As a quick example, you will remember that you used the addition operator (+) to add two strings together in previous chapters. Here is an example of two string values being combined with the addition operator:

Images

You can also use the addition operator when one of the values is a variable, as in this example:

Images

The addition operator also works when both values are variables, as in the next example:

Images

These examples illustrate how you can use many of the arithmetic operators with a number of values and/or variables. This allows you some flexibility in the way you code your scripts.

The operators that work on single values are the increment, decrement, unary plus, and unary negation operators. The increment and decrement operators are actually shortcuts to adding or subtracting 1, so learning how to use them could save you some coding time.

The arithmetic operators and their functions are summarized in Table 5-1. The following sections discuss each operator in more detail.

Images

Table 5-1   The Arithmetic Operators

The Addition Operator (+)

As you have seen, the addition operator can be used to combine two strings. It is also used to add numbers in mathematical calculations.

Variables for Addition Results

One use of the addition operator is to add two numbers to get the mathematical result. When adding numerical values, you often assign the result to a variable and use the value of the variable later. For example, to calculate the value of 4 plus 7 and show the result, you could code it like this:

Images

The result is an alert that says 11.

To make the example a little more complex, you could change one of the numbers to a variable:

Images

The result is the same as the previous example’s code: an alert that says 11.

Taking the example one step further, you could make both of the numbers variables:

Images

This example allows for the most flexibility, since you can change the values of the two number variables and get a new result without needing to dig deeper into the script to make the change.

Operands

Each value that is used with an operator is called an operand. Most operators in JavaScript work with two operands at a time. For instance, the following code contains two operands: 7 and 4.

let thesum = 7 + 4;

The values on either side of the operator are operands. This is also true when using other data types or when using variables:

Images

When using operators that take two operands in a statement multiple times, JavaScript will use the order of operations (this will be explained in the “Understanding Order of Operations” section in this chapter) and perform the tasks with one operator and two operands at a time. In the case of the addition operator, if no other operators or parentheses are present, then the order of operations will proceed from left to right. Consider the following code:

let thesum = 2 + 3 + 1;

First, the 2 + 3 portion of the expression will be calculated to get a result of 5. This result is then used as the first operand to complete the calculation, 5 + 1, which will give the final result of 6.

Some operators (called unary operators) use only one operand. The operator is placed directly before or after the lone operand. For example, take a look at this code:

Images

In this case, the increment operator is used, and the only operand is the mymoney variable. You will see more about the increment operator and the remaining unary operators as you move through this chapter.

Type Coercions in Calculations

It is important to note that JavaScript performs type coercion (attempting to change the data type of a value if it is deemed necessary) when working with the arithmetic operators. When you use the addition and other arithmetic operators, you need to be aware that JavaScript automatically coerces different values, like an integer (a nondecimal numeric value) and a float (a decimal numeric value) to the appropriate type. For instance, you might have the following code:

Images

When the script is run, you will see an alert with the result.

Images

JavaScript added the integer and the float together and gave back a float: 11.73. JavaScript does this automatically, so you need to make sure that the values you use are going to give you the results you expect.

For example, if you add a number and a string, the result will come out as though you had combined two strings. Look at this example:

Images

This looks as if it would be adding the numbers 4 and 7, since they both appear to be numbers. The trouble is that the 7 is a string in this case, not a number, because it has quotes around it. This causes the 4 to be converted to a string, and then the two strings are added together (concatenated). The result that appears in the alert box may surprise you.

Images

Rather than the expected answer of 11, you get 47. When the two values are added as strings, they are run together rather than added mathematically. With strings, “4”+“7”=47.

The other arithmetic operators also do conversions, much like the addition operator, so be aware of this possibility if you get unexpected results in a script.

Special Rules

The addition operator has some special rules it uses when trying to perform a calculation or concatenation. Here are some of the situations most commonly encountered:

   If one operand has the special value of NaN (Not a Number), and the other operand is a number, then the result will be NaN.

   If one operand is a string, the other operand is coerced into a string and the strings are concatenated.

   If both operands are strings, the strings are simply concatenated.

NOTE

If you have two numbers and then a string, the numbers will be added first and then converted. For example, 35 + 5 + “th Avenue” will first add 35+5 as numbers (since operators are evaluated from left to right), and then the result (40) will be concatenated as a string with “nth Avenue,” resulting in “40th Avenue.”

As an example of these rules in action, if NaN is added to a number, the result is NaN. If it is added to a string, the string value “NaN” will be concatenated to the other string value:

   4 + NaN will be NaN

   “Hi” + NaN will be “HiNaN”

As you proceed through this chapter, you will see that the other operators also have special rules that may be helpful to understand if you should come across unexpected results in your scripts.

The Subtraction Operator (–)

The subtraction operator is used to subtract the value on its right side from the value on its left side, as in mathematics. Here is an example:

Images

This code simply subtracts 3 (the number on the right of the operator) from 10 (the number on the left of the operator). The result is 7.

Special Rules

As with the addition operator, there are some special rules:

   If one of the operands is NaN, the result will be NaN.

   If one of the operands is of a data type other than number (for example, string, Boolean, and so on), then JavaScript attempts to coerce that value into a number and perform the subtraction. If it cannot coerce the value, the result will be NaN. For example, “7” – “3” will evaluate to 4, since these string values will be coerced into the numbers 7 and 3, respectively.

The Multiplication Operator (*)

The multiplication operator is used to multiply two operands. The next example shows this operator in action:

Images

Special Rules

   If one of the operands is NaN, the result will be NaN.

   If one of the operands is of a data type other than number, it attempts to coerce that value and perform the multiplication. If it cannot coerce the value, the result will be NaN.

The Division Operator (/)

The division operator is used to divide the value on its left side by the value on its right side. For example, the code 4 / 2 means 4 divided by 2 and gives the result of 2. For a JavaScript example of this in action, take a look at this code:

Images

The result is 5, dividing 10 by 2.

Special Rules

   If one of the operands is NaN, the result will be NaN.

   If the number zero is divided by the number zero, the result will be NaN.

   If any other finite number is divided by the number zero, the result will be the special value of Infinity.

   If one of the operands is of a data type other than number, it attempts to coerce that value and perform the division. If it cannot coerce the value, the result will be NaN.

Division by Zero

When you use the division operator, you need to be careful that you do not end up dividing by zero in some way. If you do, the result is going to be Infinity. The code that follows shows an example of this happening (although it is unlikely to occur exactly in this way):

Images

If you placed this code in a document, you might see an alert box like this:

Images

To avoid dividing by zero, be careful about what numbers or variables you place on the right side of the division operator.

The Modulus Operator (%)

The modulus operator is used to divide the number on its left side by the number on its right side, and then give a result that is the integer remainder of the division. Think back to when you learned long division and used remainders as part of the answer rather than converting to decimals or fractions. Dividing 11 by 2 gives 5 with a remainder of 1. The remainder of 1 is what the modulus operator gives you when you write 11 % 2.

The following is an example in JavaScript:

Images

The result is an alert box that shows the value of the remainder, which is 1. If the calculation had no remainder, the result would be 0.

This is the last of the arithmetic operators that work on two values at the same time. The unary operators, which work on only one value at a time, are next.

The Increment Operator (++)

The increment operator is unary and increases the value of its lone operand by 1. The effect of using it depends on whether the operator is placed before or after the operand.

The Increment Operator Before the Operand

When the increment operator is placed before the operand, it increases the value of the operand by 1, and then the rest of the statement is executed. Here is an example:

Images

In this case, the variable num1 begins with a value of 2. However, when the code assigns the value to the variable theresult, it increments the value of num1 before the assignment takes place. The increment occurs first because the increment operator is in front of the operand. So, the value of num1 is set to 3 (2+1) and is then assigned to the variable theresult, which gets a value of 3.

The Increment Operator After the Operand

If you place the increment operator after the operand, it changes the value of the operand after the assignment. Consider this example:

Images

As in the previous example, num1 begins with the value of 2. On the next line, the increment operator is used after the operand. This means that the code assigns the current value of num1 to the variable theresult, and after that is done, it increments the value of num1. So, only after this assignment is complete do you have a new value for num1. The variable theresult is given a value of 2, and then num1 is changed to 3. If you use num1 after this, it will have a value of 3.

Another way to see how the increment operator works before and after the operand is to run the following script in your browser. Notice what the values are in the first alert and what they are in the second alert.

Images

In the first alert box, you will see num1= 3 result= 3. Since the ++ operator is used before the operand here, the value of num1 is increased by 1 and then assigned to the result variable. In the second alert box, you will see num1= 3 result= 2. This is because the ++ operator is used after the operand, so the value of num1 is increased after it has been assigned to the result variable. The result variable gets a value of 2, but num1 will be increased to 3.

Note also that you do not have to perform an assignment to use this operator. You can simply type num1++; or ++num1; and the value of num1 will be changed accordingly for later use.

The Decrement Operator (– –)

The decrement operator works in the same way as the increment operator, but it subtracts 1 from the operand rather than adding 1 to it. As with the increment operator, its placement before or after the operand is important.

If you place the decrement operator before the operand, the operand is decremented, and then the remainder of the statement is executed. Here is an example:

Images

Here, the variable num1 is given a value of 2. In the next line, the code subtracts 1 from num1 and then assigns the result to the variable theresult. Thus, the variable theresult ends up with a value of 1 (2–1).

When you place the operator after the operand, as in the next example, the rest of the statement is executed and the operand is decremented afterward:

Images

This time, the variable theresult is assigned a value of 2, and then num1 is decremented to 1. If you use num1 after this line, it will have a value of 1.

The Unary Plus Operator (+)

The unary plus operator is used to try to coerce a value into a number. If it cannot coerce the value, then the result will be NaN. This is a handy operator to use when you run into the situation mentioned earlier in the chapter:

Images

As you recall, this returned the string “47”. The unary + operator could be used on the num2 variable to coerce the string “7” into its numeric value, which would then allow mathematical addition to take place rather than string concatenation.

Images

Notice the parentheses around the +num portion of the statement. As in math, you can use parentheses to set the order of operations (as you’ll learn later in this chapter) or just to clarify the order visually. Here, the parentheses aren’t necessary, but they help organize that code so that you can see that it is adding num1 to the result of using the unary plus operator on num2. You could have written this code as well:

let thesum = num1 + +num2;

This doesn’t look as nice, but it still works. The updated code will return a result of 11 rather than “47”, since the string “7” was able to be coerced into a numeric 7.

The Unary Negation Operator (–)

Unary negation is the use of the subtraction sign on only a single operand. This operator creates a negative number or negates the current sign of the number (positive or negative).

Here is an example of assigning a negative value to a number:

let negnum = -3;

This defines a variable with a value of negative 3. Basically, the operator tells the browser that the 3 is “not positive,” because it negates the default sign of positive by placing the negation operator ahead of the number.

You can also use the unary negation operator to help show the addition or subtraction of a negative number, as in this example:

let theresult = 4 + (-3);

Notice the parentheses around the –3 portion of the statement. As mentioned with the unary plus operator, this is optional and merely provides additional clarity.

You may be thinking that an even easier way to write the same thing looks like this:

let theresult = 4 - 3;

You’re right, this is the simplest way to write it; but it uses subtraction rather than unary negation.

You can also use this operator on a variable value, which simply negates the sign on the number represented by the variable:

let x = 4;
let y = 3;
let z = -y;

This assigns the variable z the unary negated value of y, which is –3.

Now that you’ve learned about the arithmetic operators, it’s time to turn to the assignment operators.

The Exponentiation Operator

The exponentiation operator allows you to define an exponent for a number, which means that the result will be the value of raising the first operand (on the left side) to the power of the second operand (on the right side). For example, to calculate two squared, or 22, you would use the following code:

var square = 2 ** 2;

In this case, the value of square will be 2 * 2, which is 4. If you want to get the cube, you can do the following:

var cube = 2 ** 3;

This time, the value will be 2 * 2 * 2, which is 8. You can do this for any power you need to get for a number.

Understanding Assignment Operators

Assignment operators assign a value to a variable. They do not compare two items, nor do they perform logical tests.

When you learned about variables in Chapter 3, you saw how the basic assignment operator, the single equal sign (=), is used to give an initial value or a new value to a variable.

The other assignment operators also give new values to variables, but they do so in slightly different ways because they perform a simple calculation as well. Table 5-2 summarizes the assignment operators, which are discussed in more detail in the following sections.

Images

Table 5-2   The Assignment Operators

The Assignment Operator (=)

You have been using the direct assignment operator since Chapter 3. It assigns the value on the right side of the operator to the variable on the left side, as in this example:

let population = 4500;

This assigns the value of 4500 to the variable population.

The Add-and-Assign Operator (+=)

The += operator adds the value on the right side of the operator to the variable on the left side and then assigns that new value to the variable. In essence, it is a shortcut to writing the type of code shown here:

let mymoney = 1000;
mymoney = mymoney + 1;

Here, the variable mymoney is created and assigned a value of 1000. The code then changes the value by assigning it a value of itself plus 1. The value assigned to the mymoney variable is 1001.

Instead of writing the variable name an extra time, you can use the add-and-assign operator to shorten the code. The following code gives the same result as the previous example, but saves a little typing:

let mymoney = 1000;
mymoney += 1;

Using the add-and-assign operator, this code adds 1 (the value on the right) to mymoney (the variable on the left), assigning the new value of 1001 to the variable mymoney.

This operator can be used to add any value, not just 1. For example, you could add 5 in the assignment, as in this example:

let mymoney = 1000;
mymoney += 5;

This time, mymoney ends up with a value of 1005.

You can even use a variable rather than a plain number value on the right side, as in this example:

let mymoney = 1000;
let bonus = 300;
mymoney += bonus;

Here, bonus has a value of 300, which is added to the variable mymoney, and then mymoney is assigned the result of 1300. In this way, the value of the bonus variable can be changed to affect the result of the assignment.

This assignment operator, like the addition arithmetic operator, also allows you to concatenate strings. Thus, you could add on to the end of a string value using this operator:

let myname = "Bob";
myname += "by";

This adds the string “by” to the end of the string “Bob”, which yields the string “Bobby”.

The Subtract-and-Assign Operator (–=)

The –= operator works like the += operator, except that it subtracts the value on the right side of the operator from the variable on the left side. This value is then assigned to the variable. Here is an example of this operator in action:

let mymoney = 1000;
let bills = 800;
mymoney -= bills;

This example subtracts the value of the bills variable (800) from the mymoney variable and assigns the result to mymoney. In the end, mymoney has a value of 200.

The Multiply-and-Assign Operator (*=)

The *= operator multiples the value on the right side of the operator by the variable on the left side. The result is then assigned to the variable. The next example shows this operator at work:

let mymoney = 1000;
let multby = 2;
mymoney *= multby;

Here, the variable mymoney is multiplied by the value of the multby variable, which is 2. The result of 2000 is then assigned to the variable mymoney.

The Divide-and-Assign Operator (/=)

The /= operator divides the variable on the left side of the operator by the value on the right side. The result is then assigned to the variable. Here is an example:

let mymoney = 1000;
let cutpayby = 2;
mymoney /= cutpayby;

In this example, the variable mymoney is divided by the value of the variable cutpayby, which is 2. The result of 500 is then assigned to the mymoney variable.

The Modulus-and-Assign Operator (%=)

Like the other assignment operators that also perform math, the %= operator does a calculation for the variable assignment. It divides the variable on the left side of the operator by the value on the right side, takes the integer remainder of the division, and assigns the result to the variable. Here is how you might assign a value to the mymoney variable using the modulus-and-assign operator:

let mymoney = 1000;
let cutpayby = 2;
mymoney %= cutpayby;

Here, the variable mymoney is divided by the value of the variable cutpayby, which is 2. The result of that is 500 with no remainder, meaning that the end result of the calculation is 0. Thus, 0 is the value that gets assigned to the variable mymoney. (If they start cutting pay like this anyplace, it is probably time to leave!)

The Exponent-and-Assign Operator (**=)

This operator raises the variable value to the power of the value on the right side of the operator and assigns the new value to the variable. Here are some examples:

let mymoney = 1000;
let exponent = 2;
mymoney **= exponent;

This time, mymoney starts out at 1000 and is raised to the power of 2. The result will be 1000 * 1000, which is 1,000,000. Now the money is looking exponentially better!

Try This 5-1Adjust a Variable Value

pr5_1.html
prjs5_1.js

In this project, you create a page that uses some of the arithmetic and assignment operators and writes the results on an HTML page.

There is more than one solution that can be used for many of these steps, so feel free to use the method you prefer. You can also try to see which method requires the least typing. Be sure to write the results of each change to the page by using the document.write() command.

Step by Step

1.   Create an HTML page and save it as pr5_1.html. Place script tags inside the body section to point to a script named prjs5_1.js.

2.   Create an external JavaScript file and save it as prjs5_1.js. Use this file for steps 3–10.

3.   Create a variable named paycheck and give it an initial value of 2000.

4.   Use an operator to increase the value of paycheck to 4000.

5.   Use an operator to decrease the value of paycheck to 3500.

6.   Use an operator to decrease the value of paycheck to 0.

7.   Use an operator to increase the value of paycheck to 500.

8.   Finally, use an operator to decrease the value of paycheck to 420.

9.   After you perform each action, write the value of the paycheck variable on the page.

10.   Save the HTML and JavaScript files and view the HTML file in your browser to see the results.

11.   A possible solution for the JavaScript file is shown in the following code, but keep in mind there are several ways to achieve the same results:

Images

Try This Summary

In this project, you were able to use your knowledge of arithmetic and assignment operators to display the results of several calculations on a Web page. This project could have been completed in numerous ways, depending on your preferences on the use of the various operators.

Understanding Comparison Operators

Comparison operators are often used with conditional statements and loops in order to perform actions only when a certain condition is met. Since these operators compare two values, they return a value of either true or false, depending on the values on either side of the operator. In later chapters, you will learn how to create a block of code to be performed only when the comparison returns true.

Table 5-3 summarizes the comparison operators, which are discussed in more detail in the following sections.

Images

Table 5-3   The Comparison Operators

The Is-Equal-To Operator (==)

For the == operator to return true, the values or statements on each side must be equal. If the values do not return as equal, the == operator returns false. Note, however, that when using this operator, type coercion is still in place, so a statement such as “4”==4 will return true because JavaScript will convert the string “4” to a number for you. If you want this statement to return false, you should use the strict is-equal-to operator (===), discussed later in this section.

Special Rules

Since this operator performs type coercion, there are some special rules:

   If one operand is a number and the other is a string, it will try to convert the string into a number before testing for equality.

   If an operand is a Boolean, then it will convert it into a numeric value before testing for equality. In such cases, true is converted to 1 and false is converted to 0.

   If one operand is null and the other is undefined, the comparison will return true.

   If one or both of the operands is NaN, the comparison will return false.

The following table shows examples of statements that use the is-equal-to operator, their return values, and the reason why they return true or false.

Images

NOTE

You will notice the addition of parentheses around some of the statements in the previous table, as well as in some of the tables that come later. Here, they are used mainly for readability. You will learn more about parentheses and the order of operations near the end of this chapter.

As with the other operators, you can use variables with comparison operators. If the values of the variables are equal, the comparison will return true. Otherwise, it will return false. Suppose that you have declared the following variables:

Images

The following comparison would return true:

num2 == num3

The next comparison would return false:

num1 == num3

CAUTION

Remember that the is-equal-to operator (==) is for comparison. Be careful not to accidentally use the assignment operator (=) in its place, because that will perform an assignment instead of a comparison and it will return the result of the assignment, so you may get some unexpected results.

The Is-Not-Equal-To Operator (!=)

The != operator is the opposite of the == operator. Instead of returning true when the values on each side of the operator are equal, the != operator returns true when the values on each side of it are not equal. This operator returns a false value if it finds that the values on both sides of the operator are equal.

As with the == operator, type coercion is in place for the != operator, and there are some special rules:

   If one operand is a number and the other is a string, it will try to convert the string into a number before testing.

   If an operand is a Boolean, then it will convert it into a numeric value before testing (true is converted to 1 and false is converted to 0).

   If one operand is null and the other is undefined, the comparison will return false.

   If one or both of the operands is NaN, the comparison will return true.

The following table shows some examples of statements that use the != operator, their return values, and the reason they return true or false.

Images

The Strict Is-Equal-To Operator (===)

For the === operator to return true, the operands on each side must be equal and must be of the same type (no type coercion is performed). This means that if you use a statement such as 3 === “3”, the operator will return false because the value on the left is a number and the value on the right is a string.

The following table shows examples of statements that use the === operator.

Images

The Strict Is-Not-Equal-To Operator (!==)

For the !== operator to return true, the values or statements on each side must not be equal or must not be of the same type (no type coercion is used). This means that if you use a statement such as 3 !== “3”, the operator will return true because the value on the left is a number and the value on the right is a string.

The following table shows some examples of statements that use the !== operator.

Images

The Is-Greater-Than Operator (>)

When the is-greater-than operator is used, the comparison returns true if the value on the left side of the operator is greater than the value on the right side. Type coercion is used, so there are some special rules:

   If both operands are strings, then the strings are compared by checking the character code of each character in both of the strings.

   If one operand is a number, then it will attempt to coerce the other operand into a number and perform the comparison.

   If an operand is a Boolean, then it is converted to a number (1 for true and 0 for false).

NOTE

The remaining comparison operators (<, >=, <=) also use these same rules.

In the case of strings, the character code of each character is used. The result is a situation where a lowercase letter is greater than an uppercase letter, and an uppercase letter is greater than a number. To look up the character code, you can use the tool at www.scripttheweb.com/js/ref/javascript-character-codes.html.

When comparing strings, JavaScript first checks the first letter of the string for a difference. If there is no difference, it moves on to the next character, then the next one, and so on, until it finds a difference or reaches the end of the string.

The following table shows some examples of statements that use the > operator.

Images

The Is-Less-Than Operator (<)

The is-less-than operator works in reverse from the is-greater-than operator. Rather than returning true when the value on the left is greater, the < operator returns true when the value on the left side of the operator is less than the value on the right side of the operator.

You can see some examples of the < operator by looking at the following table.

Images

The Is-Greater-Than-or-Equal-To Operator (>=)

The >= operator is slightly different from the comparison operators you’ve read about so far. This operator adds an option for the values on both sides to be equal and still have the comparison return true. So, to return true, the value on the left side of the operator must be greater than or equal to the value on the right side. The following table shows some examples of statements that use the >= operator.

Images

The Is-Less-Than-or-Equal-To Operator (<=)

Much like the >= operator, the <= operator adds the possibility for the values on each side to be equal. With the is-less-than-or-equal-to operator, a value of true is returned if the value on the left side of the operator is less than or equal to the value on the right side of the operator. The following table shows examples of statements that use the <= operator.

Images

You’ll get some practice using the comparison operators when you learn about conditional statements and loops in Chapter 6. Next up are the logical operators, which can be helpful to you when checking conditions.

Understanding Logical Operators

The three logical operators allow you to compare two conditional statements to see if one or both of the statements are true and to proceed accordingly. The logical operators can be useful if you want to check on more than one condition at a time and use the results. Like the comparison operators, the logical operators return either true or false, depending on the values on either side of the operator.

Table 5-4 summarizes the logical operators, which are discussed in the following sections.

Images

Table 5-4   The Logical Operators

The AND Operator (&&)

The logical operator AND returns true if the comparisons on both sides of the && operator are true. If one or both comparisons on either side of the operator are false, a value of false is returned. Some statements that use the AND operator are shown in the following table.

Images

The OR Operator (||)

The logical operator OR returns true if the comparison on either side of the operator returns true. So, for this to return true, only one of the statements on one side needs to evaluate to true. To return false, the comparisons on both sides of the operator must return false. The following table shows some examples of comparisons using the OR operator.

Images

The NOT Operator (!)

The logical operator NOT can be used on a single comparison to say, “If this is not the case, then return true.” Basically, it can make an expression that would normally return false return true, or make an expression that would normally return true return false. The following table shows some examples of this operator at work.

Images

Now that you have the regular logical operators down, take a quick look at the bitwise logical operators.

The Bitwise Operators

Bitwise operators are logical operators that work at the bit level, where there is a bunch of ones and zeros. You will not be using them in the examples presented in this book, but you may see them in some scripts on the Web. The following table lists some of the bitwise operators and their symbols, which should help you spot a bitwise operator if you see one.

Images

Special Operators

There are a number of special operators in JavaScript that are used to perform specific tasks, or to aid in shortening code. Table 5-5 lists the special operators and their purposes.

Images

Table 5-5   Special Operators

Don’t be discouraged if many of the terms used in this table look unfamiliar. Objects, arrays, and other unfamiliar terms are discussed in later chapters. Many of these operators will be reintroduced at the appropriate point in the later chapters, where their purpose can be expressed more clearly.

Understanding Order of Operations

In JavaScript, the operators have a certain order of precedence. In a statement with more than one operator involved, one may be executed before another, even though it is not in that order in the statement. For instance, look at this example:

let answer = 8 + 7 * 2;

If you remember how this works in mathematics, you will know that the multiplication is performed first on the 7*2 part of the statement, even though it does not look like that is the right order when you read from left to right. The reason the multiplication is performed first is that the multiplication operator has a higher precedence in the order of operations than the addition operator. So, any multiplication done within a statement will be performed before any addition, unless you override it somehow.

As with math problems, in JavaScript, the way to override the order of operations is through the use of parentheses to set off the portion of the statement that should be executed first. Thus, if you wanted to be sure the addition was performed first in the preceding example, you would write it as shown here instead:

let answer = (8 + 7) * 2;

If you use more than one set of parentheses or operators of the same precedence on the same level, then they are read from left to right, as in this example:

let answer = (8 + 7) - (4 * 3) + (8 - 2);

Since the parentheses are all on the same level (not nested), they are read from left to right. The addition and subtraction operators outside the parentheses have the same precedence, and thus are also read from left to right.

The precedence of the JavaScript operators is shown in Table 5-6, ranked from highest precedence (done first) to lowest precedence (done last).

Images

Table 5-6   Operator Precedence, from Highest to Lowest

As you can see in Table 5-6, parentheses override the other operators. Parentheses are handy when you are unsure of the precedence of various operators or if you want to make something more readable.

Try This 5-2True or False?

pr5_2.html
prjs5_2.js

This project will allow you to experiment with some of the comparison operators to see how they work. You will create a script that shows an alert stating whether or not a statement or comparison will return true. The script will use a conditional if/else statement, which is explained in detail in the next chapter.

Step by Step

1.   Create an HTML file and save it as pr5_2.html.

2.   Create an external JavaScript file and save it as prjs5_2.js. Use this file for editing in steps 3–13.

3.   Insert the code that follows into your JavaScript file:

Images

4.   Open the HTML page in your browser. You should instantly see an alert saying “True.”

5.   Change the value of the variable num1 to 5. Resave the JavaScript file and refresh your browser. You should now get an alert saying “False.”

6.   In the following line of code, change the == operator to the > operator:

if (num1 == num2) {

7.   Resave the JavaScript file and refresh your browser. You should get "True" again.

8.   Change the value of the variable num2 to 7.

9.   Resave the JavaScript file and refresh your browser. You should now get "False" again.

10.   In the following line (which you changed in step 4), change the operator to the < operator:

if (num1 > num2) {

11.   Resave the JavaScript file and refresh your browser. You should get “True” again.

12.   Try to change the value of the num1 variable so that you get an alert that says “False” instead.

13.   Try your own tests with the other comparison operators to see what the results will be.

Try This Summary

In this project, you were able to use your knowledge of the comparison operators to create an alert that displayed “True” or “False” depending on whether the comparison statement would return true or false. You were also able to try testing your own variations of values and operators if you desired.

Images   Chapter 5 Self Test

1.   A(n) __________ is a symbol or word in JavaScript that performs some sort of calculation, comparison, or assignment on one or more values.

2.   __________ operators are most often used to perform mathematical calculations on two values.

3.   The __________ operator adds two values.

4.   When the increment operator is placed __________ the operand, it increases the value of the operand by 1, and then the rest of the statement is executed.

5.   Which of the following is not a JavaScript operator?

A.   =

B.   ==

C.   &&

D.   $#

6.   What does an assignment operator do?

A.   Assigns a new value to a variable

B.   Gives a variable a new name

C.   Performs a comparison

D.   Nothing, because assignment operators are useless

7.   The add-and-assign (+=) operator adds the value on the __________ side of the operator to the variable on the __________ side and then assigns that new value to the variable.

8.   What does a comparison operator do?

A.   Performs a mathematical calculation

B.   Deals with bits and is not important right now

C.   Compares two values or statements, and returns a value of true or false

D.   Compares only numbers, not strings

9.   Which of the following comparisons will return true?

A.   4 != 3

B.   4 == 3

C.   4 < 3

D.   4 <= 3

10.   Which of the following comparisons will return false?

A.   4 != 3

B.   3 == 3

C.   4 > 3

D.   4 <= 3

11.   The __________ operators allow you to compare two conditional statements to see if one or both of the statements are true and to proceed accordingly.

12.   Which of the following statements will return true?

A.   (3 == 3) && (5 < 1)

B.   !(17 >= 20)

C.   (3 != 3) || (7 < 2)

D.   (1 == 1) && (2 < 0)

13.   Which of the following statements will return false?

A.   !(3 <= 1)

B.   (4 >= 4) && (5 <= 2)

C.   (“a” == “a”) && (“c” != “d”)

D.   (2<3) || (3<2)

14.   __________ operators are logical operators that work at the bit level.

15.   In JavaScript, the operators have a certain order of __________.

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

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