Math

Example 1: Math constants

The Math object provides a number of constants often-used in trigonometry and geometry, such as PI (the ratio of a circle to its diameter) and logarithms such as E (Euler’s constant, used for natural logarithms). All Math constant functions are written in uppercase e.g. PI and SQRT2. When using Math constants you do not have to provide any parameters as the value is always the same. For example, to calculate the area of a circle, use the following syntax:

var radius = 32

var area = Math.PI * radius * radius

In the example above, the Math constant function PI is multiplied by the radius squared and the result stored in a variable named area.

Example 2: Math methods

As well as Math constants the Math object provides Math methods, these allow you to perform a variety of scientific calculations, such as calculating angles with cos (cosine), sin (sine), tan (tangent) and acos, asin, atan and atan2 methods. Other Math methods allow you to perform scientific calculations such as sqrt (find the square root of a number) and pow (raise the power of one number by another). The rest of the Math functions have a variety of uses, for example, floor will round a number to the lowest integer (e.g. 3.456 will be returned as 3), while ceil does the opposite and raises a number to the highest integer (e.g. 3.456 will be returned as 4).

In the example below, the round function is used to round a number to its nearest integer

var myNum_1 = 12.49999
var round_1 = Math.round(myNum_1) // returns 12
var myNum_2 = 12.51111
var round_2 = Math.round(myNum_2) // returns 13

Note:
A simple rule to remember is that with Math constants, the functions are in uppercase letters and they do not require a parameter. With Math methods, the functions are in lowercase and require parameters.

Close