javascript

Math Object


 

Math object is a built-in object that provides mathematical constants and functions for performing mathematical operations.
Math object includes multiple methods and properties for mathematical calculation.

There is various Math object in JavaScript:
 

1. Constant

  • Math.PI: Represents the mathematical constant pi(3.14).
  • Math.E: Represents the mathematical constant e(2.71).

 

Example:

// Math Constant
console.log(Math.PI); // Output: 3.1415
console.log(Math.E); // Output: 2.7182

 

2. Basic mathematical methods

  • Math.abs(x): Returns the absolute value of a number x.
  • Math.ceil(x): Returns the smallest integer greater than or equal to a number x.
  • Math.floor(x): Returns the largest integer less than or equal to a number x.
  • Math.round(x): Rounds a number x to the nearest integer.
  • Math.max(x1, x2, ..., xn): Returns the largest of zero or more numbers.
  • Math.min(x1, x2, ..., xn): Returns the smallest of zero or more numbers.

 

Example:

// Math Methods
let absoluteValue = Math.abs(-34); // 34
let mathCeil = Math.ceil(5.2); // 6
let mathFloor = Math.floor(4.7); // 4
let mathRound = Math.round(3.6); // 4
let minNum = Math.min(10, 20, 5, 30); // 5
let maxNum = Math.max(10, 20, 5, 30); // 30

 

3. Exponential and logarithmic methods

  • Math.exp(x): Returns the value of E^x, E is Euler's number.
  • Math.log(x): Returns the natural logarithm (base E) of a number.
  • Math.pow(x, y): Returns the value of x raised to the power of y.

Example:
 

// Exponential & logarithmic methods
let mathPow = Math.pow(2, 3); // 2 raised to 3 -> 8
let mathExp = Math.exp(4); // e raised to the power of 4
let mathLog = Math.log(20); // log of 20

 

4. Random number methods

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

 

Example:
 

// Random number methods
let mathRandom = Math.random(0, 1); // value between 0 & 1