JS Math Operations

Welcome to another tutorial, here you will learn how to perform math operations in JavaScript.

 

Using the Math Object

In JavaScript, the Math object provides a number of useful methods and properties for performing mathematical tasks, such as generating random numbers, rounding numbers, obtaining values such as PI, performing a calculation, etc. It also consists of methods employed in carrying out a mathematical task that is normally impossible or too complex to perform using standard mathematical operators (e.g +, -,*, and /) such as calculating sine or cosine values.

 

The Math.PI Property

The property Math.PI represents the ratio of the circumference of a circle to its diameter. The PI (π) is a mathematical constant, which is approximately 3.14159; i.e Math.PI = π ≈ 3.14159.

Below is an example that calculates the area of a circle using Math.PI property:

// Printing PI value
document.write(Math.PI);  // Prints: 3.141592653589793
 
// Function to calculate circle area
function calculateCircleArea(radius){
    var area = (Math.PI) * radius * radius;
    return area;
}
 
document.write(calculateCircleArea(5));  // Prints: 78.53981633974483
document.write(calculateCircleArea(10));  // Prints: 314.1592653589793

Try with example

Note: In JavaScript, the Math object is a built-in object, so its properties and methods can be accessed directly. Therefore, You don’t need to create a Math object while programming, because it is automatically created by the JavaScript interpreter.

 

Getting the Absolute Value

To calculate the absolute (or positive) value of the number the Math.abs() method is used. For example; -1 is returned as 1, -5 as 5, and so on. It is demonstrated in the example:

document.write(Math.abs(-1));  // Prints: 1
document.write(Math.abs(1));  // Prints: 1
document.write(Math.abs(-5));  // Prints: 5
document.write(Math.abs(-10.5));  // Prints: 10.5

Try with example

 

Generating a Random Number

In JavaScript, the Math.random() method is used to generate a floating-point random number in the range from 0 inclusive up to but not including 1. But, when you need a random integer between zero and an integer higher than one, you could use the solution below:

document.write(Math.random());  // Expected output: a number between 0 and 1
 
// Function to create random integer 
function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}
 
document.write(getRandomInt(3));  // Expected output: 0, 1 or 2
document.write(getRandomInt(1));  // Expected output: 0

Try with example

 

Calculating the Square Root of a Number

To calculate the square root of a number the Math.sqrt() method is used; e.g Math.sqrt(x) = x. But, if the number is negative, NaN is returned. this is an example:

document.write(Math.sqrt(4));  // Prints: 2
document.write(Math.sqrt(16));  // Prints: 4
document.write(Math.sqrt(0.25));  // Prints: 0.5
document.write(Math.sqrt(-9));  // Prints: NaN
 
/* Function to calculate hypotenuse.
Hypotenuse is the longest side of a right-angled triangle. */
function calculateHypotenuse(a, b) {
    return Math.sqrt((a * a) + (b * b));
}
 
document.write(calculateHypotenuse(3, 4));  // Prints: 5
document.write(calculateHypotenuse(5, 12));  // Prints: 13

Try with example

 

Rounding Numbers

In JavaScript, the Math object provides a few methods to round numbers, each one has its purpose. Subsequent sections in this tutorial will describe these methods in details.

The ceil() Method

The Math.ceil() method can be used to round a number up to the next highest integer. For instance, 3.5 becomes 4, -5.7 becomes -5 (because -5 is greater than -6). Below is an example:

document.write(Math.ceil(3.5));  // Prints: 4
document.write(Math.ceil(-5.7));  // Prints: -5
document.write(Math.ceil(9.99));  // Prints: 10
document.write(Math.ceil(-9.99));  // Prints: -9
document.write(Math.ceil(0));  // Prints: 0

Try with example

 

The floor() Method

The Math.floor() method can be used to round a number down to the next lowest integer. For instance, 3.5 becomes 3, -5.7 becomes -6 (because -6 is lesser than -5). Below is an example:

document.write(Math.floor(3.5));  // Prints: 3
document.write(Math.floor(-5.7));  // Prints: -6
document.write(Math.floor(9.99));  // Prints: 9
document.write(Math.floor(-9.99));  // Prints: -10
document.write(Math.floor(0));  // Prints: 0

Try with example

 

The round() Method

The Math.round() method can be used to round a number to the nearest integer in a way that if the decimal part is ‘.5’ or greater, the number is rounded up, otherwise rounded down; as such, 3.5 becomes 4, -5.7 becomes -6, 4.49 becomes 4, etc. below is an example:

document.write(Math.round(3.5));  // Prints: 4
document.write(Math.round(-5.7));  // Prints: -6
document.write(Math.round(7.25));  // Prints: 7
document.write(Math.round(4.49));  // Prints: 4
document.write(Math.round(0));  // Prints: 0

Try with example

 

Finding the Largest and Smallest Numbers

In JavaScript, the largest or smallest can be found in a group of numbers by using the Math.max() and Math.min() methods, respectively. below is an example:

document.write(Math.max(1, 3, 2));  // Prints: 3
document.write(Math.max(-1, -3, -2));  // Prints: -1
 
document.write(Math.min(1, 3, 2));  // Prints: 1
document.write(Math.min(-1, -3, -2));  // Prints: -3

Try with example

 

With the apply() method, you can also find the maximum or minimum value within an array or an array-like object, this is shown in the example below:

var numbers = [1, 3, 2];
 
document.write(Math.max.apply(null, numbers));  // Prints: 3
document.write(Math.min.apply(null, numbers));  // Prints: 1

Try with example

 

There is an even simpler way to do this, by using the ECMAScript 6. Here, you can accomplish the same thing using the new spread operator (...), as shown in the example below:

var numbers = [1, 3, 2];
 
document.write(Math.max(...numbers));  // Prints: 3
document.write(Math.min(...numbers));  // Prints: 1

Try with example

 

Raising Numbers to a Power

To raise a number to a specified power the Math.pow() method is used. The expression Math.pow(xy) is equivalent to mathematically xy; it shows how many times the base x is multiplied by the exponent y. This is an example:

document.write(Math.pow(3, 2));  // Prints: 9
document.write(Math.pow(0, 1));  // Prints: 0
document.write(Math.pow(5, -2));  // Prints: 0.04
document.write(Math.pow(16, 0.5));  // Prints: 4 (square root of 4)
document.write(Math.pow(8, 1/3));  // Prints: 2 (cube root of 8)

Try with example

Note: Here, a positive exponent indicates multiplication (52 = 5 x 5 = 25), a negative exponent indicates division (5-2 = 1/52 = 0.04), and a fractional exponent indicates a root of the base.

 

Performing Trigonometric Operations

In JavaScript, the Math object also provides numerous trigonometric methods such as sin(), cos(), tan() to perform trigonometric operations. But, this method works in radians, therefore, you have to multiply any degree measurements by π/180 before using them.

Note: Pi radians are equal to 180 degrees: i.e. π rad = 180°. so, π/2 radians = 90°, π/3 radians = 60°, and so on. An example is shown below:

document.write(Math.sin(0 * Math.PI / 180));  // Prints: 0
document.write(Math.sin(90 * Math.PI / 180));  // Prints: 1
document.write(Math.cos(0 * Math.PI / 180));  // Prints: 1
document.write(Math.cos(180 * Math.PI / 180));  // Prints: -1
document.write(Math.tan(0 * Math.PI / 180));  // Prints: 0

Try with example