DEV Community

Tandap Noel Bansikah
Tandap Noel Bansikah

Posted on

JavaScript Math()

JavaScript Math is a built-in object in JavaScript that provides a set of mathematical functions and constants. It makes complex mathematical calculations much easier in JavaScript.

Here are some of the most commonly used functions of the Math object:

  1. Math.round(): This function rounds a number to the nearest integer. For example,

let x = 4.6;
x = Math.round(x);// would return 5

console.log(x);.
Enter fullscreen mode Exit fullscreen mode

2.Math.floor(): This function returns the largest integer less than or equal to a given number. For example,

let x  = 4.6;

x = Math.floor(x);// would return 4

console.log(x);
Enter fullscreen mode Exit fullscreen mode

3.Math.ceil(): This function returns the smallest integer greater than or equal to a given number. For example,

let x = 4.6;
Math.ceil(x); / would return 5.
Enter fullscreen mode Exit fullscreen mode

4.Math.abs(): This function returns the absolute value of a number. For example,

let x  = -4.6;

x = Math.abs(x);// would return 4.6

console.log(x);
Enter fullscreen mode Exit fullscreen mode

5.Math.sqrt(): This function returns the square root of a given number. For example,

let x  = 16;

x = Math.sqrt(x);// would return 4

console.log(x);
Enter fullscreen mode Exit fullscreen mode

6.Math.pow(): This function returns the value of a number raised to a given power. For example,

let x  = 2;

x = Math.pow(x,3);// would return 8

console.log(x);
Enter fullscreen mode Exit fullscreen mode

7.Math.min(): This function returns the smallest of two or more numbers. For example,

let x  = 2;
let y = 12;
let z = 5;
let minimum;
let maximum;

minimum = Math.min(x,y,z);// would return 2

console.log(minimum);
Enter fullscreen mode Exit fullscreen mode

8.Math.max(): This function returns the largest of two or more numbers. For example,

let x  = 2;
let y = 12;
let z = 5;
let minimum;
let maximum;

maximum = Math.max(x,y,z);// would return 12

console.log(maximum);
Enter fullscreen mode Exit fullscreen mode

9.Math.random(): This function returns a random number between 0 and 1. For example, Math.random() would return a number like 0.384729473.

10.Build in constants: There are also some build in constants. For example,

let x;
x = Math.PI;// would return 3.141592653589793
console.log(x);
Enter fullscreen mode Exit fullscreen mode

In addition to these functions, the Math object also contains a number of useful constants, such as Math.E (which represents the value of e).

In conclusion, the Math object in JavaScript is an incredibly useful tool for performing mathematical calculations in your code. By using the functions and constants provided by the Math object, you can make your code much more efficient and streamlined. This is just to name a few there are so many more. Adios

Top comments (0)