Publishers of technology books, eBooks, and videos for creative people

# How to Work with Simple Variable Types in JavaScript

• Print
This chapter is from the book

## Working with Numbers

Unlike a lot of languages, JavaScript only has a single number type, used to represent any numerical value, from integers to doubles (i.e., decimals or real numbers) to exponent notation. You can rest assured in knowing that numbers in JavaScript can safely represent values up to around 9 quadrillion!

Let’s look at everything you need to know about numbers in JavaScript, from the arithmetic operators to formatting numbers, to using the Math object for more sophisticated purposes.

### Arithmetic Operators

You’ve already been introduced to one operator: a single equals sign, which is the assignment operator. JavaScript supports the standard arithmetic operators, too (Table 4.1).

#### Table 4.1. Arithmetic Operators

 SYMBOL MEANING + Addition - Subtraction * Multiplication / Division % Remainder

The modulus operator, in case you’re not familiar with it, returns the remainder of a division. For example:

`var remainder = 7 % 2; // 1;`

One has to be careful when applying the modulus operator to negative numbers, as the remainder itself will also be negative:

`var remainder = -7 % 2; // -1`

These arithmetic operators can be combined with the assignment operator to both perform a calculation and assign the result in one step:

```var cost = 50; // Dollars

cost *= 0.7373; // Converted to euros```

You’ll frequently come across the increment and decrement operators: ++ and --. The increment operator adds one to the value of the variable; the decrement operator subtracts one:

```var num = 1;

num++; // 2

num--; // 1```

These two operators can be used in both prefix and postfix manners (i.e., before the variable or after it):

```var num = 1;

num++; // num now equals 2.

++num; // num is now 3.

--num; // num is now 2.```

A difference between the postfix and prefix versions is a matter of operator precedence. The rules of operator precedence dictate the order operations are executed in a multi-operation line. For example, basic math teaches that multiplication and division have a higher precedence than addition and subtraction. Thus:

`var num = 3 * 2 + 1; // 7, not 9`

Table 4.2 lists the order of precedence in JavaScript, from highest to lowest, including some operators not yet introduced (I’ve also omitted a couple of operators that won’t be discussed in this book). There’s also an issue of associativity that I’ve omitted, as that would be just one more thing you’d have to memorize. In fact, instead of trying to memorize that table, I recommend you use parentheses to force, or just clarify, precedence, without relying upon mastery of these rules. For example:

`var num = (3 * 2) + 1; // Still 7.`

That syntax, while two characters longer than the earlier version, has the same net effect but is easier to read and undeniably clear in intent.

Some of the operators in Table 4.2 are unary, meaning they apply to only one operand (such as ++ and --); others are binary, applying to two operands (such as addition). In Chapter 5, you’ll learn how to use the one trinary operator, which has three operands.

#### Table 4.2. Operator Precedence

 PRECEDENCE OPERATOR NOTE 1 . [] member operators 1 new creates new objects 2 () function call 3 ++ -- increment and decrement 4 ! logical not 4 + - unary positive and negative 4 typeof void delete 5 * / % multiplication, division, and modulus 6 + - addition and subtraction 8 < <= > >= comparison 9 == != === !== equality 13 && logical and 14 || logical or 15 ?: conditional operator 16 = += -= *= /= %= <<= >>= >>>= &= ^= |= assignment operators

The last thing to know about performing arithmetic in JavaScript is if the result of the arithmetic is invalid, JavaScript will return one of two special values:

• NaN, short for Not a Number
• Infinity

For example, you’ll get these results if you attempt to perform arithmetic using strings or when you divide a number by zero, which surprisingly doesn’t create an error (Figure 4.2). In Chapter 5, you’ll learn how to use the isNaN() and isFinite() functions to verify that values are numbers safe to use as such. Figure 4.2. The result of invalid mathematical operations will be the special values NaN and Infinity.

### Creating Calculators

At this point in time, you have enough knowledge to begin using JavaScript to perform real-world mathematical calculations, such as the kinds of things you’d put on a Web site:

• Mortgage and similar loan calculators
• Temperature and other unit conversions
• Interest or investment calculators

For this particular example, let’s create an e-commerce tool that will calculate the total of an order, including tax, and minus any discount (Figure 4.3). The most relevant HTML is:

```<div><label for="quantity">Quantity</label><input type="number"
name="quantity" id="quantity" value="1" min="1" required></div>

<div><label for="price">Price Per Unit</label><input type="text"
name="price" id="price" value="1.00" required></div>

<div><label for="tax">Tax Rate (%)</label><input type="text"
name="tax" id="tax" value="0.0" required></div>

<div><label for="discount">Discount</label><input type="text"
name="discount" id="discount" value="0.00" required></div>

<div><label for="total">Total</label><input type="text"
name="total" id="total" value="0.00"></div>

<div><input type="submit" value="Calculate" id="submit"></div>``` Figure 4.3. A simple calculator.

That would go in a page named shopping.html, which includes the shopping.js JavaScript file, to be written in subsequent steps. You’ll notice that the HTML form makes use of the HTML5 number input type for the quantity, with a minimum value. The other types are simply text, as the number type doesn’t deal well with decimals. Each input is given a default value, and set as required. Remember that as Chapter 2, JavaScript in Action, explains, browsers that don’t support HTML5 will treat unknown types as text elements and ignore the unknown properties. The final text element will be updated with the results of the calculation.

To create a calculator:

1. Create a new JavaScript file in your text editor or IDE, to be named shopping.js.
2. Begin defining the calculate() function:
```function calculate() {

'use strict';```

This function will be called when the user clicks the submit button. It does the actual work.

3. Declare a variable for storing the order total:
`var total;`

As mentioned previously, you should generally declare variables as soon as you can, such as the first line of a function definition. Here, a variable named total is declared but not initialized.

4. Get references to the form values:
```var quantity = document.getElementById('quantity').value;

var price = document.getElementById('price').value;

var tax = document.getElementById('tax').value;

var discount = document.getElementById('discount').value;```

In these four lines of code, the values of the various form elements are assigned to local variables. Note that in the Chapter 2 example, variables were assigned references to the form elements, and then the element values were later checked. Here, the value is directly assigned to the variable.

At this point in time, one would also perform validation of these values, prior to doing any calculations. But as Chapter 5 more formally covers the knowledge needed to perform validation, I’m skipping this otherwise needed step in this example.

5. Calculate the initial total:
`total = quantity * price;`

The total variable is first assigned the value of the quantity times the price, using the multiplication operator.

6. Factor in the tax rate:
```tax /= 100;

tax++;

total *= tax;```

There are a couple of ways one can calculate and add in the tax. The first, shown here, is to change the tax rate from a percent (say 5.25%) to a decimal (0.0525). Next, add one to the decimal (1.0525). Finally, multiply this number times the total. You’ll see that the division-assignment, incrementation, and multiplication-assignment operators are used here as shorthand. This code could also be written more formally:

```tax = tax/100;

tax = tax + 1;

total = total * tax;```

You could also make use of precedence and parentheses to perform all these calculations in one line.

An alternative way to calculate the tax would be to convert it to decimal, multiply that value times the total, and then add that result to the total.

7. Factor in the discount:
`total -= discount;`

The discount is just being subtracted from the total.

8. Display the total in the form:
`document.getElementById('total').value = total;`

The value attribute can also be used to assign a value to a text form input. Using this approach, you can easily reflect data back to the user. In later chapters, you’ll learn how to display information on the HTML page using DOM manipulation, rather than setting the values of form inputs.

9. Return false to prevent submission of the form:
`return false;`

The function must return a value of false to prevent the form from actually being submitted (to the page named by the form’s action attribute).

10. Complete the function:
`} // End of calculate() function.`
11. Define the init() function:
```function init() {

'use strict';
`var theForm = document.getElementById('theForm');`
`theForm.onsubmit = calculate;`

} // End of init() function.```

The init() function will be called when the window triggers a load event (see Step 12). The function needs to add an event listener to the form’s submission, so that when the form is submitted, the calculate() function will be called. To do that, the function gets a reference to the form, by calling the document object’s getElementById() method, providing it with the unique ID value of the form. Then the variable’s onsubmit property is assigned the value calculate, as explained in Chapter 2.

`window.onload = init;`

This code was also explained in Chapter 2. It says that when the window has loaded, the init() function should be called.

It’s a minor point, as you can organize your scripts in rather flexible ways, but this line is last as it references the init() function, defined in Step 12, so that definition should theoretically come before this line. That function references calculate(), so the calculate() function’s definition is placed before the init() function definition. You don’t have to organize your code this way, but I prefer to. Figure 4.4. The result of the total order calculation.

Play with the numbers, including invalid values (Figure 4.5), and retest the calculator until you’re comfortable with how arithmetic works in JavaScript. Figure 4.5. Performing arithmetic with invalid values, such as a quantity of cat, will result in a total of NaN.

### Formatting Numbers

Although the previous example is perfectly useful, and certainly a good start, there are several ways in which it can be improved. For example, as written, no checks are made to ensure that the user enters values in all the form elements, let alone that those values are numeric (Figure 4.5) or, more precisely, positive numbers. That knowledge will be taught in the next chapter, which discusses conditionals, comparison operators, and so forth. Another problem, which can be addressed here, is that you can’t expect someone to pay, say, 22.1336999 (Figure 4.4). To improve the professionalism of the calculator, formatting the calculated total to two decimal points would be best.

A number in JavaScript is not just a number, but is also an object of type Number. As an object, a number has built-in methods, such as toFixed(). This method returns a number with a set number of digits to the right of a decimal point:

```var num = 4095.3892;

num.toFixed(3); // 4095.389```

Note that this method only returns the formatted number; it does not change the original value. To do that, you’d need to assign the result back to the variable, thereby replacing its original value:

`num = num.toFixed(3);`

If you don’t provide an argument to the toFixed() method, it defaults to 0:

```var num = 4095.3892;

num.toFixed(3); // 4095```

The method can round up to 20 digits.

Similar to toFixed() is toPrecision(). It takes an argument dictating the total number of significant digits, which may or may not include those after the decimal.

Let’s apply this information to the calculator in order to add some better formatting to the total.

To format a number:

1. Open shopping.js in your text editor or IDE, if it is not already.
2. After factoring in the discount, but before showing the total amount, format the total to two decimals:
`total = total.toFixed(2);`

This one line will take care of formatting the decimal places. Remember that the returned result must be assigned back to the variable in order for it to be represented upon later uses.

Alternatively, you could just call total.toFixed(2) when assigning the value to the total form element. Figure 4.6. The same input as in Figure 4.4 now generates a more appropriate result.

An even better way of formatting the number would be to add commands indicating thousands, but that requires more logic than can be understood at this point in the book.

### The Math Object

You just saw that numbers in JavaScript can also be treated as objects of type Number, with a couple of built-in methods that can be used to manipulate them. Another way to manipulate numbers in JavaScript involves the Math object. Unlike Number, you do not create a variable of type Math, but use the Math object directly. The Math object is a global object in JavaScript, meaning it’s always available for you to use.

The Math object has several predefined constants, such as π, which is 3.14... and E, which is 2.71... A constant, unlike a variable, has a fixed value. Conventionally, constants are written in all uppercase letters, as shown. Referencing an object’s constant uses the same dot syntax as you would to reference one of its methods: Math.PI, Math.E, and so forth. Therefore, to calculate the area of a circle, you could use (Figure 4.7):

```var radius = 20; Figure 4.7. The area of a circle, πr2, is calculated using the Math.PI constant.

The Math object also has several predefined methods, just a few of which are:

• abs(), which returns the absolute value of a number
• ceil(), which rounds up to the nearest integer
• floor(), which rounds down to the nearest integer
• max(), which returns the largest of zero or more numbers
• min(), which returns the smallest of zero or more numbers
• pow(), which returns one number to the power of another number
• round(), which returns a number rounded to the nearest integer
• random(), which returns a pseudo-random number between 0 (inclusive) and 1 (exclusive)

There are also several trigonometric methods like sin() and cos().

Another way of writing the formula for determining the area of a circle is:

```var radius = 20;

var area = Math.PI * Math.pow(radius, 2);```

To apply this new information, let’s create a new calculator that calculates the volume of a sphere, based upon a user-entered radius. That formula is:

`volume = 4/3 * π * radius 3`

Besides using the π constant and the pow() method, this next bit of JavaScript will also apply the abs() method to ensure that only a positive radius is used for the calculation (Figure 4.8). The relevant HTML is:

```<div><label for="radius">Radius</label><input type="text" name="radius" id="radius" required></div>

<div><label for="volume">Volume</label><input type="text" name="volume" id="volume"></div>

<div><input type="submit" value="Calculate" id="submit"></div>``` Figure 4.8. This calculator determines and displays the volume of a sphere given a specific radius.

The HTML page includes the sphere.js JavaScript file, to be written in subsequent steps.

To calculate the volume of a sphere:

1. Create a new JavaScript file in your text editor or IDE, to be named sphere.js.
2. Begin defining the calculate() function:
```function calculate() {

'use strict';

var volume;```

Within the function, a variable named volume is declared, but not initialized.

3. Get a reference to the form’s radius value:
`var radius = document.getElementById('radius').value;`

Again, this code closely replicates that in shopping.js, although there’s only one form value to retrieve.

4. Make sure that the radius is a positive number:
`radius = Math.abs(radius);`

Applying the abs() method of the Math object to a number guarantees a positive number without having to use a conditional to test for that.

5. Calculate the volume:
`volume = (4/3) * Math.PI * Math.pow(radius, 3);`

The volume of a sphere is four-thirds times π times the radius to the third power. This one line performs that entire calculation, using the Math object twice. The division of four by three is wrapped in parentheses to clarify the formula, although in this case the result would be the same without the parentheses.

6. Format the volume to four decimals:
`volume = volume.toFixed(4);`

Remember that the toFixed() method is part of Number, which means it’s called from the volume variable, not from the Math object.

7. Display the volume:
`document.getElementById('volume').value = volume;`

This code is the same as in the previous example, but obviously referencing a different form element.

8. Return false to prevent the form’s submission, and complete the function:
```    return false;

} // End of calculate() function.```
9. Add an event listener to the form:
```function init() {

'use strict';
document.getElementById('calcForm').onsubmit = calculate;
} // End of init() function.