JavaScript Math Reference

Posted by

JavaScript Math Reference

The Math object provides a number of useful properties and methods which can be used to perform mathematical operations. This tutorial will cover how to use the various properties and methods of the Math object.

Properties

The Math object includes several properties that can be used to retrieve useful values, such as the value of pi, epsilon, and the maximum and minimum values that can be stored in a number.

  • Math.E: Returns Euler’s number (2.718)
  • Math.LN2: Returns the natural logarithm of 2 (0.693)
  • Math.LN10: Returns the natural logarithm of 10 (2.303)
  • Math.LOG2E: Returns the base 2 logarithm of E (1.442)
  • Math.LOG10E: Returns the base 10 logarithm of E (0.434)
  • Math.PI: Returns the value of pi (3.14)
  • Math.SQRT1_2: Returns the square root of 1/2 (0.707)
  • Math.SQRT2: Returns the square root of 2 (1.414)

Methods

The Math object also includes several methods that can be used to perform different mathematical operations. These methods include:

  • Math.abs(x): Returns the absolute value of x
  • Math.acos(x): Returns the arccosine of x, in radians
  • Math.asin(x): Returns the arcsine of x, in radians
  • Math.atan(x): Returns the arctangent of x, in radians
  • Math.ceil(x): Returns the value of x rounded up to the nearest integer
  • Math.cos(x): Returns the cosine of x, in radians
  • Math.exp(x): Returns the value of Ex
  • Math.floor(x): Returns the value of x rounded down to the nearest integer
  • Math.log(x): Returns the natural logarithm (base E) of x
  • Math.max(x,y): Returns the number with the highest value (either x or y)
  • Math.min(x,y): Returns the number with the lowest value (either x or y)
  • Math.pow(x,y): Returns the value of x to the power of y
  • Math.random(): Returns a random number between 0 and 1
  • Math.round(x): Returns the value of x rounded to the nearest integer
  • Math.sin(x): Returns the sine of x, in radians
  • Math.sqrt(x): Returns the square root of x
  • Math.tan(x): Returns the tangent of x, in radians

Examples

Here are a few examples of how you can use some of the methods and properties of the Math object:

  • Calculating the square root of a number:
    • Math.sqrt(25); // returns 5
  • Randomly generating a number between 0 and 10:
    • Math.floor(Math.random() * 10); // returns a random number between 0 and 10
  • Rounding a number to the nearest integer:
    • Math.round(5.5); // returns 6
  • Calculating the sine of a number:
    • Math.sin(90); // returns 1
  • Retrieving the value of pi:
    • Math.PI; // returns 3.14

Conclusion

The Math object in JavaScript provides a number of useful properties and methods which can be used to perform various mathematical operations. This tutorial has provided an overview of the Math object, along with some examples of how to use it. For more detailed information, please refer to the official JavaScript documentation.