Course: JavaScript

Progress (0%)

# JavaScript Math Object

Chapter 17 9 mins

Learning outcomes:

1. Useful mathematical constants — Math.PI and Math.E
2. Finding the minimum and maximum number
3. Rounding numbers to the nearest integer
4. Truncating numbers
5. Other useful functions

## Introduction

Apart from the very basic Number object in JavaScript, we have a behemoth for working with numbers in countless ways — the Math object.

Math comes with a whole ton of properties and methods for dealing with numbers in a multitude of ways. It has got functions for calculating angles, logs; flooring or ceiling numbers; generating random numbers; and a lot more.

A number-intensive JavaScript application like a point-of-sale program or a game can't do much without using the Math object.

In this chapter, we'll consider the useful bucket of properties and methods available on the Math object. To work best with this giant object, it is recommended that you already know concepts in maths like trigonometry, logarithms, indices, etc.

## Useful mathematical constants

First things first, let's begin with the properties of Math:

### Math.PI

Math.PI holds the value of the mathematical constant $\pi$, known as pi:

Math.PI
3.141592653589793

Recall from JavaScript Variables — Rules for naming variables that the name PI is case-sensitive; writing pI orpi would return undefined.

### Math.E

Math.E holds the value of the mathematical constant $e$, known as Euler's number.

Math.E
2.718281828459045

## Minimum and maximum

The min() and max() methods of Math can be used to find the minimum and the maximum of a given set of numbers, respectively.

The numbers are provided as separate arguments to the methods.

Let's consider some examples:

Math.min(0, 1)
0
Math.min(-Infinity, Infinity)
Infinity
Math.min(-1, 0, 10, 20, -5)
-5
Math.min(3, 2, 1)
1

Keep in mind that min() and max() do NOT accept an array of numbers; we have to provide the numbers separately.

But what if we have the numbers in the form of an array?

Well, in that case, we can manually use a syntactical construct in JavaScript to render a list of arguments from a given array. It is the spread operator (...).

Here are a couple of examples:

Math.min(...[0, 1])
0
Math.min(...[-Infinity, Infinity])
-Infinity
Math.min(...[-1, 0, 10, 20, -5])
-1

The array value is preceded by three dots, which represent the spread operator (...). This operator serves to spread an array into a list of arguments for a given function.

We shall see this construct in more detail in JavaScript Functions — Arguments.

## Rounding to the nearest integer

In the last chapter, JavaScript Numbers — Number Methods, we saw how to represent numbers formatted to a given significant figure or decimal place precision, while also rounding them where necessary.

The result of each rounding function was a string because otherwise representing the formatted numbers would be impossible if the number type was continued to be used.

However, sometimes we want to stick to the number type and round a given number to the nearest integer. In this case, we can use the round() method of Math.

Math.round(num)

The method takes in the number to round.

If the number's fractional part is equal to .5, round() rounds to the nearest integer in the direction of ∞. This might pose an issue when dealing with half-way negative numbers, e.g. -0.5, -1.5, etc. In other instances, round() works mostly as we're accustomed to in day-to-day mathematics.

Following are some examples:

Math.round(1)
1
Math.round(1.5)
2
Math.round(1.4)
1
Math.round(1.7)
2
Math.round(-1.4)
-1
Math.round(-1.5)
-1
Math.round(-1.7)
-2

The only strange outcome in this code might be of rounding -1.5; we might expect it to become -2 but round() returns -1 (since its tie-breaking rule is to round the number upwards).

If we wish to round a half-way negative number downwards instead of upwards, we can create our own rounding function. This is left as an exercise for you to complete in the upcoming part of this unit.

## Truncating a number

Truncation is a familiar operation in mathematics whereby the fractional part of a number is truncated off the number.

For example, truncating 1.123 would give 1. Similarly, truncating 1.78 would give 1 again. For negative numbers, truncating -1.123 and -1.78 would give -1.

The trunc() method of Math is used to perform this operation in JavaScript.

Math.trunc(num)

The method takes in the number to truncate.

Following are some examples:

Math.trunc(1)
1
Math.trunc(1.4)
1
Math.trunc(1.7)
1
Math.trunc(-1.4)
-1
Math.trunc(-1.7)
-1
Math.trunc(0.7)
0
Math.trunc(-0.7)
-0

There is a nice relationship between the truncation function and the floor and ceil functions in mathematics. Let's see if you can figure it out.

See the relationship
$\text{trunc}(x) = \begin{cases} \lfloor x \rfloor &\text{if } x \ge 0 \\ \lceil x \rceil &\text{if } x < 0 \end{cases}$

## Useful mathematical functions

Now let's explore some commonly-used methods of the Math object that mirror common mathematical functions.

### Math.abs()

Math.abs() returns the absolute value of a number.

Math.abs(2); // returns 2
Math.abs(-2); // returns 2
Math.abs(-2.5); // returns 2.5

### Math.random()

Math.random() returns a pseudo-random number between 0 (inclusive) and 1 (exclusive):

Math.random()
0.6657972268679888
Math.random()
0.4394964707564588
Math.random()
0.10890352976104811

### Math.sin(), Math.cos() and Math.tan()

Math.sin(), Math.cos(), and Math.tan() return the sine, cosine, and tangents of given angles (in radians), respectively.

// same as sin(0.5π) in maths
Math.sin(0.5 * Math.PI); // returns 1
Math.cos(0.5 * Math.PI); // returns 6.123233995736766e-17 that's almost 0

// Trick to return calculator value
Math.round(Math.cos(0.5 * Math.PI)); // returns 0
Math.tan(0.25 * Math.PI); // returns 0.9999999999999999

// Same trick
Math.round(Math.tan(0.25 * Math.PI)); // returns 1

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage