JavaScript : Math Object

In JavaScript, the Math object provides a set of properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks and calculations easily in your JavaScript code. Here's an overview of the Math object and its commonly used properties and methods:

1. Mathematical Constants:

 

  • Math.PI: Represents the ratio of the circumference of a circle to its diameter, approximately 3.14159.
  • Math.E: Represents Euler's number, the base of natural logarithms, approximately 2.718.

2. Common Mathematical Functions:

 

  • Math.abs(x): Returns the absolute value of a number.
  • Math.round(x): Returns the value of a number rounded to the nearest integer.
  • Math.ceil(x): Returns the smallest integer greater than or equal to a number.
  • Math.floor(x): Returns the largest integer less than or equal to a number.
  • Math.max(x1, x2, ...): Returns the largest of zero or more numbers.
  • Math.min(x1, x2, ...): Returns the smallest of zero or more numbers.
  • Math.pow(x, y): Returns the base to the exponent power.
  • Math.sqrt(x): Returns the square root of a number.
  • Math.random(): Returns a pseudo-random number between 0 and 1.

3. Trigonometric Functions:

 

  • Math.sin(x): Returns the sine of a number (in radians).
  • Math.cos(x): Returns the cosine of a number (in radians).
  • Math.tan(x): Returns the tangent of a number (in radians).
  • Math.asin(x): Returns the arcsine of a number (in radians).
  • Math.acos(x): Returns the arccosine of a number (in radians).
  • Math.atan(x): Returns the arctangent of a number (in radians).
  • Math.atan2(y, x): Returns the arctangent of the quotient of its arguments.

4. Other Functions:

 

  • Math.log(x): Returns the natural logarithm (base e) of a number.
  • Math.exp(x): Returns Euler's number raised to the power of a number.
  • Math.abs(x): Returns the absolute value of a number.
  • Math.sign(x): Returns the sign of a number (1, -1, or 0).

Example Usage:


console.log(Math.PI); // Output: 3.141592653589793
console.log(Math.round(4.7)); // Output: 5
console.log(Math.pow(2, 3)); // Output: 8
console.log(Math.sqrt(16)); // Output: 4
console.log(Math.random()); // Output: (random number between 0 and 1)
console.log(Math.sin(Math.PI / 2)); // Output: 1 (sine of 90 degrees in radians)

 

These are just some of the functions and properties provided by the Math object in JavaScript. It's a powerful tool for performing mathematical operations in your code.