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!).
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:
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!
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:
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.
Use the editor below to practice using the Math properties and methods. The following are a few ideas that you can try implementing: