15. Numbers


In This Chapter

Make sense of numbers

Learn about the variety of numerical values you will encounter

Meet the Math object and the various mathematical things you can do


When you are not dealing with strings, a large part of your time in JavaScript will be spent dealing with numbers. Even if you aren’t working with numbers directly, you’ll indirectly encounter them when doing even the most basic of tasks such as keeping count of something, working with arrays, and so on.

In this chapter, I will provide an introduction to numbers in JavaScript by looking at how you can use them to accomplish many common tasks. Along the way, we will dive a little bit beyond the basics to broadly explore some interesting number-related things you might find useful.

Onwards!

Using a Number

In order to use a number, all you have to do is...well, use it. Below is a simple example of me declaring a variable called stooges that is initialized to the number 3:

var stooges = 3;

That is it. There are no hoops to jump through. If you want to use more complex numbers, just use them as if nothing is different:

var pi = 3.14159;
var color = 0xFF;
var massOfEarth = 5.9742e+24;

In the above example, I am using a decimal value, a hexadecimal value, and a really large value using exponents. In the end, your browser will automatically do the right thing. Note that the “right thing” doesn’t just exist in the positive space. You can use negative numbers easily as well. To use negative numbers, just place a minus (-) character before the number you want to turn into a negative value:

var temperature = −42;

What you’ve seen in this section makes up the bulk of how you will actually use numbers. In the next couple of sections, let’s go a little bit deeper and look at some of the other interesting things you can do with numbers.

Operators

No introduction to numbers would be complete (...or started) without showing you how you can use mathematical operators in code to implement things you learned in first-grade Math class.

Let’s look at the common operators in this section.

Doing Simple Math

In JavaScript, you can create simple mathematical expressions using the +, -, *, /, and % operators to add, subtract, multiply, divide, and find the remainder (modulus) of numbers respectively. If you can use a calculator, you can do simple math in JavaScript.

Here are some examples that put these operators to use:

var total = 4 + 26;
var average = total / 2;
var doublePi = 2 * 3.14159;
var removeItem = 50–25;
var remainder = total % 7;
var more = (1 + average * 10) / 5;

In the last line in the above example, notice that I am defining a particular order of operations by using parentheses around the expression I want to evaluate as a group. Again, all of this is just calculator stuff.

JavaScript evaluates expressions in the following order:

1. Parenthesis

2. Exponents

3. Multiply

4. Divide

5. Add

6. Subtract

There are various mnemonic devices out there to help you remember this. The one I grew up with since elementary school is “Please Excuse My Dear Aunt Sally.”

Incrementing and Decrementing

A common thing you will do with numbers involves incrementing or decrementing a variable by a certain amount. Below is an example of me incrementing the variable i by 1:

var i = 4;
i = i + 1;

You don’t have to increment or decrement by just 1. You can use any arbitrary number:

var i = 100;
i = i - 2;

All of this doesn’t just have to just be addition or subtraction. You can perform other operations as well:

var i = 40;
i = i / 2;

You should start to see a pattern here. Regardless of what operator you are using, you’ll notice that you are cumulatively modifying your i variable. Because of how frequently you will use this pattern, you have some operators that simplify this a bit (see Table 15.1).

Image

TABLE 15.1 Operators

If I use these operators on the three examples you saw earlier, the code will look as follows:

i++;
i -= 2;
i /= 2;

Before we wrap this up, there is one quirk you should be aware of. It has to do with the -- and ++ operators for incrementing or decrementing a value by 1. Whether the ++ and -- operators appear before or after the variable they are incrementing matters.

Let’s look at this example:

var i = 4;
var j = i++;

After executing these two lines, the value of i will be 5...just like you would expect. The value of j will be 4. Notice that in this example, the operator appears after the variable.

If we place the operator in front of the variable, the results are a bit different:

var i = 4;
var j = ++i;

The value of i will still be 5. Here is the kicker...the value of j will also be 5.

What changed between these two examples is the position of the operator. The position of the operator determines whether the incremented value or the preincremented value will be returned. Now, aren’t you glad you learned that?

Special Values—Infinity and NaN

The last thing we will look at are two special/reserved keywords that you will encounter that aren’t numerical values. These values are Infinity and NaN.

Infinity

You can use the Infinity and Infinity values to define infinitely large or small numbers:

var reallyBigNumber = Infinity;
var reallySmallNumber = -Infinity;

The chances of you having to use Infinity are often very slim. Instead, you will probably see it returned as part of something else your code does. For example, you will see Infinity returned if you divide by 0.

NaN

The NaN keyword stands for “Not a Number”, and it gets returned when you do some numerical operation that is invalid. For example, NaN gets returned in the following case:

var oops = Math.sqrt(-1);

The reason is that you cannot divide a number and a string. There are non-contrived cases where you will see this value returned. The parseInt function I described earlier will return a NaN if the string you are converting is invalid.

The Math Object

Numbers are used in a variety of mathematical expressions, and they often go beyond simple addition, subtraction, multiplication, and division. Your math classes back in the day would have been a whole lot easier if that’s all there was to it. To help you more easily do complicated numerical things, you have the Math object. This object provides you with a lot of functions and constants that will come in handy, and we are going to very briefly look at some of the things this object does.

The Constants

To avoid you having to explicitly define mathematical constants like Pi, Euler’s constant, LN10, and so on, the Math object defines many common constants for you:

Image

Of all of these constants, the one I’ve used the most is Math.PI:

Image

You will use this in everything from drawing circles on your screen to specifying trigonometric expressions. In fact, I can’t ever remember having used any of these other constants outside of Math.PI. Here is an example of a function that returns the circumference given the radius:

function getCircumference(radius) {
    return 2 * Math.PI * radius;
}

alert(getCircumference(2));

You would use Math.PI or any other constant just as you would any named variable.

Rounding Numbers

Your numbers will often end up containing a ridiculous amount of precision:

var position = getPositionFromCursor(); //159.3634493939

To help you round these numbers up to a reasonable integer value, you have the Math.round(), Math.ceil(), and Math.floor() functions that take a number as an argument:

Image

The easiest way to make sense of the above table is to just see these three functions in action:

Math.floor(.5); // 0
Math.ceil(.5); // 1
Math.round(.5); // 1

Math.floor(3.14); // 3
Math.round(3.14); // 3
Math.ceil(3.14); // 4

Math.floor(5.9); // 5
Math.round(5.9); // 6
Math.ceil(5.9); // 6

These three functions always round you to an integer. If you want to round to a precise set of digits, check out the last half of the Rounding Numbers in JavaScript tutorial at the following location: http://bit.ly/kirupaRounding.

Trigonometric Functions

My favorite among all the functions, the Math object, gives you handy access to almost all of the trigonometric functions you will need.

Image

To use any of these, just pass in a number as the argument:

Math.cos(0); // 1
Math.sin(0); // 0
Math.tan(Math.PI / 4); // 0.9999999999999999
Math.cos(Math.PI); // -1
Math.cos(4 * Math.PI); // 1

These trigonometric functions take arguments in the form of radian values. If your numbers are in the form of degrees, be sure to convert them to radians first.

Powers and Square Roots

Continuing down the path of defining the Math object functions, you have Math.pow(), Math.exp(), and Math.sqrt():

Image

Let’s look at some examples:

Math.pow(2, 4) //equivalent of 2^4 (or 2 * 2 * 2 * 2)
Math.exp(3) //equivalent of Math.E^3
Math.sqrt(16) //4

Note that Math.pow() takes two arguments. This might be the first built-in function we’ve looked at that takes two arguments. This little detail is somehow mildly exciting.

Getting the Absolute Value

If you want the absolute value of a number, simply use the Math.abs() function:

Math.abs(37) //37
Math.abs(-6) //6

The way this function works is pretty predictable if you looked at these in school. If you pass in a negative number, it returns the positive variant of it.

Random Numbers

To generate a somewhat random number between 0 and a smidgen less than 1, you have the Math.random() function. This function doesn’t take any arguments, but you can simply use it as part of a mathematical expression:

var randomNumber = Math.random() * 100;

Each time your Math.random function is called, you will see a different number returned for Math.random(). To learn all about how to work with this function to generate random numbers, read the Random Numbers in JS tutorial here: http://bit.ly/kirupaRandom.


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


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

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