# Coding Arithmetic

Many students discover that a problem can be simple while taking page after page of calculations to solve. It’s during these plodding moments that one begins to lament, “There must be a better way.”

In fact, that better way is precisely what the inventors of the first computers had running through their minds. And today, you can use programming to instruct your computer to handle tedious calculations, while focusing your attention on the interesting aspects of a problem. Our goal here is to show you how.

In this post, we’ll touch on how to use JavaScript for arithmetic operations and some related functions. We start by demonstrating how easy it is to use JavaScript as a basic calculator to, say, compute the area of a circle with radius 8.

#### Arithmetic Operations

For addition and subtraction, the JavaScript notation is identical to that of a calculator. For other arithmetic operations, the notation differs but is relatively straightforward. Compare the math and JavaScript counterparts in the following table.

Operation Math Notation JavaScript Notation
Addition $a+b$ a + b
Subtraction $a-b$ a - b
Multiplication $a\times b$ a * b
Division $a\div b$ a / b
Modulus $a\mod{b}$ a % b
Power $a^b$ Math.pow(a, b)
Exponential $e^a$ Math.exp(a)
Square Root $\sqrt{a}$ Math.sqrt(a)
Natural Logarithm $\ln{a}$ Math.log(a)
Absolute Value $|a|$ Math.abs(a)

Not too complicated, is it? Here are a few of the operations in actions. Try opening up the code and playing around with different operations and values.

console.log(1 + 1); // 2
console.log(9 / 3); // 3
console.log(Math.pow(2, 2)); // 4
console.log(Math.sqrt(25)); // 5
console.log(Math.abs(-6)); // 6


You might be wondering what the deal is with the Math prefix on some of these functions. The simple symbols such as + are called operators. The Math prefix indicates that these operations are either properties (e.g., PI, E) or methods (e.g., pow(), sqrt()) of a global object called Math. We’ll give a more detailed explanation of objects, properties, and methods in a later post.

#### Mathematical Constants

There are numbers that come up often in mathematics but are rather unwieldy to work with. JavaScript provides a quick and easy way to use them.

Constant Approximation JavaScript Notation
$\pi$ $3.14159$ Math.PI
$e$ $2.718$ Math.E
$\sqrt{2}$ $1.414$ Math.SQRT2
$\sqrt{\frac{1}{2}}$ $0.707$ Math.SQRT1_2
$\ln{2}$ $0.693$ Math.LN2
$\ln{10}$ $2.302$ Math.LN10
$\log_{2}{e}$ $1.442$ Math.LOG2E
$\log{e}$ $0.434$ Math.LOG10E

Compare the approximations in the table above to the values given in JavaScript.

console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045
console.log(Math.SQRT2); // 1.4142135623730951
console.log(Math.SQRT1_2); // 0.7071067811865476
console.log(Math.LN2); // 0.6931471805599453
console.log(Math.LN10); // 2.302585092994046
console.log(Math.LOG2E); // 1.4426950408889634
console.log(Math.LOG10E); // 0.43429448190325176


#### Trigonometric Functions

In addition to arithmetic operations, JavaScript has a number of built-in trigonometric functions.

Operation Math Notation JavaScript Notation
Sine $\sin a$ Math.sin(a)
Cosine $\cos a$ Math.cos(a)
Tangent $\tan a$ Math.tan(a)
Arcsine $\sin^{-1} a$ Math.asin(a)
Arccosine $\cos^{-1} a$ Math.acos(a)
Arctangent $\tan^{-1} a$ Math.atan(a)
Arctangent $\tan^{-1} \frac{a}{b}$ Math.atan2(a, b)

Note that these functions take radians rather than degrees as input, where $\mathrm{rad} = \mathrm{deg} \times \frac{\pi}{180}$. If you forget to convert degrees to radians, you’ll get back an unexpected answer, as illustrated in the following example.

console.log(Math.sin(90)); // 0.8939966636005579
console.log(Math.sin(90 * Math.PI / 180)); // 1


#### Integer Operations

The next set of operations convert any kind of number to an integer. The round function rounds the number down to the nearest integer if the decimal part is less than .5, and rounds the number up if it’s .5 or greater. The floor function always rounds the number down to the nearest integer (i.e., returning whatever is to the left of the decimal point in the original number). The ceiling function always rounds the number up to the nearest integer.

Operation Math Notation JavaScript Notation
Round $[a]$ Math.round(a)
Floor $\lfloor a \rfloor$ Math.floor(a)
Ceiling $\lceil a \rceil$ Math.ceil(a)

console.log(Math.round(0.2)); // 0
console.log(Math.floor(0.2)); // 0
console.log(Math.ceil(0.2)); // 1

console.log(Math.round(99 / 2)); // 50
console.log(Math.floor(99 / 2)); // 49
console.log(Math.ceil(99 / 2)); // 50


#### Other Handy Functions

Here are other built-in JavaScript functions that are useful for manipulating numbers. The first three functions introduce a slightly different notation where the command is appended to a number, indicating that it is a method of that number.

JavaScript Notation Description
a.toFixed(b) Formats number a with b decimal places.
a.toPrecision(b) Formats number a with b significant digits.
a.toExponential(b) Formats number a with b significant digits in scientific notation.
Math.max(a, b, c,...) Returns the maximum value from one or more inputs.
Math.min(a, b, c,...) Returns the minimum value from one or more inputs.
Math.random() Returns a random number from 0 up to but not including 1.

Here are the functions in action. Click the code to open in a new tab, and observe the output of Math.random() when you execuute it multiple times.

console.log(987.654321.toFixed(4)); // 987.6543
console.log(987.654321.toPrecision(4)); // 987.7
console.log(987.654321.toExponential(4)); // 9.8765e+2

console.log(Math.max(7, 6.8, -9)); // 7
console.log(Math.min(7, 6.8, -9)); // -9

console.log(Math.random());


#### Operator Precedence

With more than one operation possible in a single statement, you should be aware of the order in which JavaScript evaluates them. From math class, "Please Excuse My Dear Aunt Sally" might ring a bell as a way of remembering the order of operations. Arithmetic operations aren't necessarily calculated left to right, but rather follow this order:

• Parentheses
• Exponentiation
• Multiplication and Division

For example, in the following expression, 2 is squared first, 4 is multiplied next, and 3 is added last.

$3 + 4 \times 2 ^ 2 = 19$

JavaScript follows an operator precedence that similarly determines the sequence in which code is evaluated.

• Level 2: Function Calls (e.g., Math.pow(), Math.round())
• Level 5: Multiplication, Division, and Modulus
• Level 6: Addition and Subtraction

As with arithmetic, parentheses are your friends. They can be used to clarify or override the operator precedence.

console.log(3 + 4 * Math.pow(2, 2)); // 19
console.log(3 + (4 * Math.pow(2, 2))); // 19
console.log((3 + 4) * Math.pow(2, 2)); // 28
console.log(Math.pow(3 + 4 * 2, 2)); // 121


JavaScript has many, many more operators, which range from level 1 all the way down to level 17 in operator precedence. The curious minded can view the full table here.

#### Special Numbers

You might have also learned in math class that it's impossible to divide by zero, that it's undefined. Most programming languages take a strict stance on dividing by zero, throwing an error whenever it occurs. JavaScript takes a more laid-back approach, returning one of three special numbers: Infinity, -Infinity, and NaN.

Dividing a positive number by zero returns Infinity, while dividing a negative number by zero returns -Infinity. Dividing zero by zero returns NaN, which stands for "Not a Number."

Infinity, -Infinity, and NaN can be used within operations as well.

console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(0 / 0); // NaN

console.log(Infinity + 1); // Infinity
console.log(1 / Infinity); // 0
console.log(Infinity / Infinity); // NaN

console.log(NaN + 1); // NaN
console.log(1 / NaN); // NaN
console.log(NaN / NaN); // NaN


#### Putting It All Together

Recall that in the beginning of this post, we mentioned calculating $A = \pi r^2$ for a circle with radius 8. Now you're equipped with all the knowledge you need to write a program to do it for you. Start by multiplying $\pi$ with the square of 8. Next, format it to two decimal places. Include a label with your result by putting quotes around text and attaching it with a + operator. Send this expression to the console, and voilà!

console.log("Area: " + (Math.PI * Math.pow(8, 2)).toFixed(2)); // Area: 201.06


Continue to Testing Algebra to learn how to define variables, assign them values, and use them to test algebraic expressions.

One Comment
1. Great of Prada reaches approximately replicate graphics of the legitimate article, or imitation Gucci bags. Reproduction Prada totes which were web-site louis vuitton brasil developed with seven get rolling handbags fantastic are fast-becoming the in factor on earth louis vuitton sito ufficiale borse of designer for the reason that the level of clutches offered plus the sheer amount of decisions in existence. louis vuitton tasche The Facebook or twitter Sites operate also allows you to definitely gain authentic-time figures about folks which can be faithful for your web based business.