Please enable JavaScript to use CodeHS

Math Object in JavaScript

By Ryan Hart

JavaScript does something clever to help programmers use common math functions and constants in their work – it provides a Math object that has properties (constants) and methods (functions) that programmers can use without any additional importing. Remember, an object is simply a variable that can contain a variety of types of information. To access this information, you write Math.[property or method name] (note “Math” must be capitalized!).

Math Properties

The Math object properties are stored values for common mathematical constants. For example, to use the constant pi, you just need to type: Math.PI. This value can be stored in another variable or used right in a calculation, like:

var circumference = 2 * Math.PI * radius;
Plain text

This makes calculations super easy! Without the Math object, in order to use the value of pi, we would have needed to know a circle’s radius and circumference to calculate it, or manually typed in its many digits ourselves.

See the example below for other math constants accessible through the Math object. Try performing a calculation with them, like the circumference of a circle with radius 4!

Math Methods

In addition to the built-in constants, the Math object contains common math operations and functions stored as object methods. The syntax is very similar to the Math properties, except you use a function( ) notation after the Math..

Below is a list of some of the available methods, where x is a number:

Math.round(x)    // rounds x to the nearest integer
Math.ceil(x)    // rounds x up to the nearest integer
Math.floor(x)    // rounds x down to the nearest integer
Math.sign(x)    // returns -1, 0, or 1 if the number is negative, 0, or positive

Math.pow(x, y)    // raises x to the power of y
Math.sqrt(x)     // takes the square root of x
Math.abs(x)     // returns the absolute value of x
Math.random()     // returns a random number between 0 and 1

Math.sin(x)     // returns the sine of x (given in radians)
Math.cos(x)     // returns the cosine of x (given in radians)
Math.tan(x)     // returns the tangent of x (given in radians)
Plain text

See the example below for some of these methods in action! Try changing the value of x or adding a few more methods from the list above.

Now it’s your turn!

Use the editor below to practice using the Math properties and methods. The following are a few ideas that you can try implementing:

  • Print the area of a circle with a radius of 6
  • Print the cosine of 3π / 4
  • Print the value of the hypotenuse on a right triangle if the two other side lengths are 5 and 8 (hint: use Pythagorean theorem – C^2 = A^2 + B^2)