# Javascript Math Tutorial: How to do Math in Javascript

## 📣 Sponsor

In all programming languages, performing mathematical operations is done routinely. Adding, subtracting, and many other operations are all required in any application. In Javascript, we can do this through simple operations, and by leveraging the Javascript `Math`

object.

**Note:** to do mathematical operations, we need to be comparing numbers. A number that is in quotation marks will not work in mathematical operations.

## Mathematical Operations

Let's take a look at a simple mathematical operation how we can use maths in variables which we covered here. Basic maths operations work just the same as if we were to write them on paper:

```
let i = 1;
let j = i + 10;
```

Above, we have defined a variable `i`

. We then define another variable, `j`

, which is equal to `i`

plus 10. Therefore, when we refer to `j`

in our code, it will return 11.

There are a bunch of other mathematical operations we can do. Let's take a look at them all.

### Javascript Arithmetic Operators

Operator | What it does | Code example |

+ | Adds two numbers together | `10 + 5` returns 15 |

- | Subtract one number from another | `10 - 5` returns 5 |

+ | Divide one number by another | `10 / 5` returns 2 |

* | Multiply two numbers together | `10 * 5` returns 50 |

% | Get the remainder of a calculation | `12 % 5` returns 2 (12 divided by 5 leaves a remainder of 2) |

** | Raises one number to the power of another | `2 ** 3` returns 8 (2 to the power of 3 is 8) |

let x = 12; let y = 15; let add = x + y; let remainder = x % y; let raiseToPower = x ** y; let divide = x / y; console.log("Addition: " + add); console.log("Remainder: " + remainder); console.log("To the Power: " + raiseToPower); console.log("Divide: " + divide);

## Math Constants

Apart from being able to do basic maths with operators in Javascript, we also have the **Math** object in Javascript. This object lets us access mathematical constants and do some more complicated maths.

Let's start by looking at Mathematical **constants** Below is an example of how we can access PI.

```
let pi = Math.PI; // returns 3.141...
```

In Javascript, we use a dot to note the specific child of the **Math** object. These are all predefined, so they exist as part of basic Javascript. The above code will return the value PI - but most common mathematical constants are available in Javascript. These irrational numbers are all listed below, and can be used in the same way as a normal number:

Mathematical Constant | What it does | Value |

Math.PI | Returns PI | 3.141 ... |

Math.E | Returns Euler's number | 2.718 ... |

Math.E | Returns Euler's number | 2.718 ... |

Math.LN2 | Returns ln(2) | 0.693 ... |

Math.LOG10E | Returns log10(e) | 0.434 ... |

Math.LOG2E | Returns log2(e) | 1.442 ... |

Math.LN10 | Returns ln(10) | 2.302 ... |

Math.SQRT2 | Returns the square root of 2 | 1.414 ... |

Math.SQRT1_2 | Returns the square root of 1/2 | 0.707 ... |

## Mathematical Notation in Javascript

If you are used to working in a mathematics environment, you will be used to scientific or mathematic notation. We can use mathematical notation in Javascript. A mathematic notation for **3124** could be written as 3.124e3.

```
let myMathNotation = 3.124e3
console.log(myMathNotation);
```

We use e to refer to the exponent. The above is the same as writing **3.124 x 10 ^{3}**.

## Rounding and Static Methods

We can use the **Math** object to do some more complicated mathematics, using functions that are built into it. These functions take a number as a value, and then adjust it accordingly. Let's look at a few examples.

### Abs

`Math.abs`

takes a number and returns its absolute value. All that means, is it makes it positive if it was negative, and keeps it positive if it already was. It is the equivalent of the mathematic concept of magnitude.

```
let absoluteNumber = Math.abs(-2); // Returns 2.
```

### Floor

`Math.floor`

takes a number and rounds it **down**. This will only work with decimals.

```
let roundItDown = Math.floor(2.8371); // Returns 2.
```

### Ceil

`Math.ceil`

takes a number and rounds it **up**. This will only work with decimals.

```
let roundItDown = Math.ceil(2.8371); // Returns 3.
```

### Round

`Math.round`

takes a number and rounds it. This will only work with decimals.

```
let roundItDown = Math.ceil(1.453); // Returns 1.
```

### Max

`Math.max`

takes a set of numbers separated by commas, and picks the **biggest** one.

```
let biggestNumber = Math.max(2, 3, 6); // Returns 6.
```

### Min

`Math.min`

takes a set of numbers separated by commas, and picks the **smallest** one.

```
let smallestNumber = Math.min(2, 3, 6); // Returns 2.
```

## More Static Methods

These useful operations let us manipulate or perform mathematical operations on numbers.

### Pow

`Math.pow`

takes a number, and raises it to a certain power. It is similar to the `**`

arithmetic operator we looked at earlier.

```
let toThePower = Math.pow(2, 3); // Returns 8, i.e. 2 to the power of 3.
```

### Sign

`Math.sign`

takes a number, and returns it sign. **Not to be confused with sin**

```
let getSign = Math.sign(-14); // Returns -1
let getAnotherSign = Math.sign(14); // Returns 0
```

### Trunc

`Math.trunc`

takes a number, and returns only the integer part of it.

```
let truncIt = Math.trunc(14.2431); // Returns 14
```

### Sqrt

`Math.sqrt`

takes a number, and returns its square root.

```
let sqrtIt = Math.sqrt(4); // Returns 2
```

### Cbrt

`Math.sqrt`

takes a number, and returns its cube root.

```
let cbrtIt = Math.sqrt(8); // Returns 2
```

### Random

`Math.random`

returns a random number between 0 and 1.

```
let randomNumber = Math.random(); // As an example, may return 0.4845737088624795
```

### Logs

There are a number of ways to do logs in Javascript, all of which are shown below:

```
let naturalLog = Math.log(10); // The natural log of 10
let log10 = Math.log10(10); // The base 10 log of 10
let log2 = Math.log2(10); // The base 2 log of 10
let log2 = Math.log1p(10); // The natural log of 1 + 10
```

## Operations for Geometry

There are a whole host of operations we can run to manipulate and calculate geometry. A list of these geometry functions are shown below. For all of these, it is assumed that the number is in **radians**.

As well as the basic sin, cos and tan operations, we also have functions for the arc versions of each (denoted with an **a** in front of the function), and the hyperbolic versions (denoted with an **h** at the end).

```
let x = 1.4;
// Geometry mathematical functions
Math.sin(x);
Math.cos(x);
Math.tan(x);
Math.asin(x);
Math.acos(x);
Math.atan(x);
Math.sinh(x);
Math.cosh(x);
Math.tanh(x);
Math.asinh(x);
Math.acosh(x);
Math.atanh(x);
```

## ParseFloat and ParseInt

Being able to do maths in Javascript is great, but if you remember from our article on types, a number written as a string will not be treated as a number in Javascript. To change a number which is a string, such as `"5"`

to a real number, we can use the function `parseFloat`

(which changes the number to a float), or `parseInt`

, which changes the number to an integer - the difference of course being that an integer has no decimals, while a float does.

Both of these functions accept both numbers, and numbers in mathematical notation.

For example:

```
let myNumber = "12345" // type: String
let myOtherNumber = "1.3453"; // type: String
// Let's parse our numbers
let parseNumber = parseFloat(myNumber); // Returns 12345 type: Number
let parseNumber = parseFloat(myOtherNumber); // Returns 1.3453 type: Number
let parseNumber = parseInt(myOtherNumber); // Returns 1 type: Number
```

These functions are very useful in vanilla Javascript, where types are not always consistent. Using these, we can take numbers stuck in strings and convert them to real numeric types which we can do calculations with.

## Conclusion

Javascript has a lot of interesting ways to do mathematics, and provides many of the common mathematical constants through the `Math`

object. As well as that, we have a number of static functions we can use to manipulate numbers through the same `Math`

function. We've learned how to use all of these in this guide, as well as how to coerce a string of numbers into a number with `parseInt`

/`parseFloat`

. All of these techniques are important concepts in Javascript, and really useful when building applications.

## More Tips and Tricks for Javascript

- Instagram Style Video Preload Static Effect
- Websockets Tutorial: Creating a real-time Websocket Server
- A Look at the New Array Methods coming to Javascript
- Javascript loops: for vs forEach vs for.. in vs for.. of
- Updating Object Key Values with Javascript
- Asynchronous Operations in Javascript
- Resolving HTTP Cannot set headers after they are sent to the client in Node.JS
- Javascript Ordinals: Adding st, nd, rd and th suffixes to a number
- An Introduction to Javascript Objects
- Javascript Shallow Copies - what is a Shallow Copy?