Working with Arithmetic Operators and Functions - JavaScript Basics - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART I JavaScript Basics

LESSON 3 Working with Arithmetic Operators and Functions

image

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonjavascript/.

In the previous lesson, you saw a few examples of operators in action, such as the + sign used either for addition or for concatenating strings together, the - sign used for subtraction, and the = operator used for assigning values.

But JavaScript supports many more operators than that, such as *, /, and more, and also includes functions you can use for more advanced expression evaluation, such as Math.sin(), Math.sqrt(), and many others. In this lesson I’ll explain all of these, how they work, and how to use them.

This is an important lesson as it covers much of the foundation of how JavaScript works, so even if you have programmed before using another language, I recommend you read this thoroughly, because there are a number of things JavaScript handles in a unique manner.

Arithmetic Operators

The arithmetic operators in JavaScript are the ones that allow you to create numeric expressions, and there are more than simply addition, subtraction, multiplication, and division, as shown in Table 3-1.

TABLE 3-1 The Arithmetic Operators

image

You can try these operators out for yourself by loading the file math_operators.htm from the companion archive into a browser, which should look like Figure 3-1. Try changing the various values and operators applied, and check the results you get.

image

FIGURE 3-1 The arithmetic operators in use

The first four of these operators should be very clear to you, so I’ll only explain the last three, starting with the modulus operator, %. What this operator returns is simply the remainder after calculating a division. For example, the modulus of 12 and 4 (calculated using the expression 12 % 4) is 0, because 4 goes into 12 an exact number of times, and therefore there is no remainder.

On the other hand, the modulus of 24 and 5 (calculated as 24 % 5) is 4, because 5 goes into 24 four times (5 multiplied by 4 is 20), leaving a remainder of 4, the modulus of the expression.

Now let’s look at the increment and decrement operators. These come in tremendously handy because without them you would have to write expressions like this:

a = a + 1

This is cumbersome when you only want to increment (or decrement) a value by 1, and so the creators of JavaScript allow you to use the following syntax instead:

++a

I’m sure you will agree this is much shorter and sweeter. It also comes with fringe benefits because the increment and decrement operators can be used within flow control commands such as if() statements (which I explain in full detail in Lesson 10, but will give you a sample here).

Consider the following code, which assumes that Time contains a 24-hour time value between 0 and 23, and which is set up to trigger once an hour, on the hour (using code not shown here, but which is assumed to be in place):

image

This code first increments the value in Time by 1, because this code has been called on the hour, so it’s now one hour since the last time it was called, and so Time must be updated. Then on the next line it displays the time in the browser (using a call to the document.write() function) prefaced by The time is.

After that, an if() statement is reached, which tests the variable Time to see whether it currently has a value of less than 12. If so, then it must still be the morning and so the string AM is output. Otherwise, it’s the afternoon and so PM is displayed—fairly straight-forward stuff.

image

This is a simple version of the if() statement in that it has only a single statement after the if, and there is also only a single one after else. Therefore, no curly braces are used to enclose the action statements. Please see Lesson 10 for greater detail on using if() and else with multistatement actions.

However, programmers always like to write the tightest and cleanest code possible, and so the following code is considered better programming practice, as it removes an entire line of code, like this (with the incremented variable and operator highlighted):

image

Pre-incrementing

What has occurred in the previous example is an instance of pre-incrementing the variable Time. In other words, before the value in Time is used, it is incremented. Only after this incrementing is the current value in Time used for displaying in the document.write() statement.

In Figure 3-2 these three lines of code have been called three times, with an original starting value for Time of 9 (using the file inc_and_dec.htm from the companion archive).

image

FIGURE 3-2 Using the increment operator

Post-incrementing

You may also place the ++ increment operator after a variable name, and then it is known as post-incrementing. What happens when you do this is that the value in the variable being incremented is looked up before the increment, and that value is used by the code accessing it. Only after this value has been looked up is the variable incremented.

The following code illustrates this type of incrementing by displaying both the before and after values in the variable a (with instances of the variable and increment operator highlighted):

document.write(’a was ′ + a++ + ′ and is now ’ + a)

Working through this statement from left to right, first the string a was is output, then a++ is displayed. This results in the current value of a being displayed, and only then is a incremented. After this the string and is now is output, followed by the new value in a, which now contains the incremented value from the earlier increment operation. Therefore, if a had an initial value of 10, the following is displayed:

a was 10 and is now 11

Pre- and Post-decrementing

You can use the decrement operator in exactly the same way as the increment operator, and it can either be placed before a variable for pre-decrementing or after for post-decrementing. Following are two examples that both display the same but achieve the result using pre-decrementing for the first and post-decrementing for the second (with instances of the variable and decrement operator highlighted):

image

Here, if b had an initial value of 10, the following is displayed:

b was 10 and is now 9
b was 9 and is now 8

image

If it’s still not entirely clear which type of increment or decrement operator to use out of pre- and post-methods, don’t worry; just use the pre-methods (with the operator before the variable) for now, because it will become obvious to you when the time comes that you actually have a need to use the post-method (with the operator after the variable).

Arithmetic Functions

To accompany the arithmetic operators, JavaScript comes with a library of arithmetic functions you can call on, as follows (the initial uppercase M in Math is necessary because JavaScript is case-sensitive):

Math.abs(a) Returns a as a positive number (or 0 if a is 0).

Math.acos(a) Returns the arccosine of a.

Math.asin(a)Returns the arcsine of a.

Math.atan(a)Returns the arctangent of a.

Math.atan2(a,b)Returns the arctangent of a / b.

Math.ceil(a)Rounds up to return the integer closest to a.

Math.cos(a)Returns the cosine of a.

Math.exp(a)Returns the exponent of a (Math.E to the power a).

Math.floor(a)Rounds down to return the integer closest to a.

Math.log(a)Returns the log of a base e.

Math.max(a,b)Returns the maximum of a and b.

Math.min(a,b)Returns the minimum of a and b.

Math.pow(a,b)Returns a to the power b.

Math.random()Returns a floating point random number greater than or equal to 0, but less than 1 (from 0 to 0.999…).

Math.round(a)Rounds up or down to return the integer closest to a.

Math.sin(a)Returns the sine of a.

Math.sqrt(a)Returns the square root of a.

Math.tan(a)Returns the tangent of a.

You should be familiar with most of these. For example, to return the square root of 64, you use the following:

Math.sqrt(64) // Returns 8

But there are a couple that need a little more explaining, such as Math.abs(). What this does is take any value (negative, zero, or positive), and if it is negative, turn it into a positive value, like this:

image

The other function needing extra explanation is Math.random(). This returns a floating point value with a statistically random value (although not truly random) between 0 and 1. Therefore, for example, if you have to emulate a 12-sided dice, you must multiply the result of the function call and turn it into an integer, like this:

Math.floor(Math.random() * 12) // Returns 0 – 11

This expression returns a value between 0 and 11.999 recurring, which is first turned into an integer, by dropping the floating point part of the number using the Math.floor() function. The result is a value between 0 and 11.

image

If, for example, you need your random number to be a value between 1 and 12 (rather than 0 through 11), simply add 1 to this result.

Assignment Operators

Like many other languages, JavaScript likes to help you out by offering more efficient ways to achieve results. One of these ways is by letting you combine assignment and arithmetic operators into six different types of assignment operators.

This typically saves lines of code and makes your program code much easier to write, and for others to understand.

Table 3-2 lists the assignment operators available, provides examples of them in use, and shows the result of doing so when the variable a already contains the value 21. You can see the result of using the expressions in this table in Figure 3-3, created with the example fileassignment_operators.htm from the accompanying archive.

TABLE 3-2 The Assignment Operators

image

image

FIGURE 3-3 Using the various assignment operators

Therefore, for example, instead of using a = a + 5, you can use the more compact a += 5. And you can use assignment operators in conjunction with other expressions and variables, as with the following example, which results in a having a value of 15 (10 + (25 / 5)):

a = 10
b = 25
a += (b / 5)

Summary

By now you should be seeing how JavaScript is actually quite a simple and graceful language, with many similarities to the natural flow of English (and similar written languages). Using it should be making good sense to you, especially now that you can make a wide range of mathematical operations—the core of any computer language.

In the following chapter we will turn our attention to comparison and logical operators, which you can use to make decisions, the second most important ability a computer language provides.

Self-Test Questions

Test how much you have learned in this lesson with these questions. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in Appendix A.

1. What does the ++ operator do?

2. What is the difference between ++a and a++?

3. What is the purpose of the % operator?

4. Which operator assigns a value to a variable?

5. What operator increments a variable by a specified value?

6. How can you turn a value from negative to positive?

7. How can you create a random number with a value between 1 and 60 inclusive?

8. Which three functions turn a floating point number into an integer?

9. Which arithmetic operator is also the string concatenation operator?

10. What is a more compact way of writing a = a / 20?