JS Math Object

JS Math Object

 

In JavaScript, the Math object provides a set of methods and properties for mathematical operations. Some of the commonly used methods and properties are:

  • Math.PI: Returns the value of PI (3.141592653589793).
  • Math.abs(x): Returns the absolute value of x.
  • Math.ceil(x): Returns the smallest integer greater than or equal to x.
  • Math.floor(x): Returns the largest integer less than or equal to x.
  • Math.round(x): Returns the value of x rounded to the nearest integer.
  • Math.max(x1, x2, …, xn): Returns the largest of the given numbers.
  • Math.min(x1, x2, …, xn): Returns the smallest of the given numbers.
  • Math.pow(x, y): Returns the value of x raised to the power of y.
  • Math.sqrt(x): Returns the square root of x.
  • Math.exp(x): Returns the value of Euler’s number (e) raised to the power of x.
  • Math.log(x): Returns the natural logarithm (base e) of x.
  • Math.sin(x): Returns the sine of x, where x is in radians.
  • Math.cos(x): Returns the cosine of x, where x is in radians.
  • Math.tan(x): Returns the tangent of x, where x is in radians.
  • Math.asin(x): Returns the arcsine of x, where the result is in radians.
  • Math.acos(x): Returns the arccosine of x, where the result is in radians.
  • Math.atan(x): Returns the arctangent of x, where the result is in radians.
  • Math.random(): Returns a random number between 0 (inclusive) and 1 (exclusive).

For example, we can use the Math object to generate a random number between 1 and 10 using the following code:

				
					const randomNum = Math.floor(Math.random() * 10) + 1;
				
			

This code first generates a random number between 0 and 9 using Math.random(), multiplies it by 10, rounds it down to the nearest integer using Math.floor(), and finally adds 1 to get a random number between 1 and 10.

Note that the Math object is a static object, which means that its methods and properties can be called directly without creating an instance of the object.

Join To Get Our Newsletter
Spread the love