Page 3 of 7
The Math object is static, so you don't need to create a new Math object in order to use it. To access the properties and method of the Math object, you merely specify the Math object, along with the method or property you wish. For example, to return the value of pi, you use:
var pi = Math.PI;
Similarly, to use a math method you provide the name of the method, along with the parameters you wish to use. For example, to round the value of pi, you'd use:
var pi = Math.PI; var pieAreRound = Math.round(pi); // displays 3
Note that you must specify the Math object by name for each Math method/property you wish to use. JavaScript does not recognize
the keywords PI and round all by themselves. Exception: you may use the with statement to associate the names of methods and properties with the Math object. This technique is a handy space-saver when
you must use several Math properties and methods. The previous example can be written as
with (Math) {
var pi = PI;
var pieAreRound = round(pi);
alert (pieAreRound)
}
For your reference, here are the properties and methods supported by JavaScript's Math object.
| E | Euler's constant |
| LN2 | The natural logarithm of 2 |
| LN10 | The natural logarithm of 10 |
| LOG2E | The base 2 logarithm of e |
| LOG10E | The base 10 logarithm of e |
| PI | The numeric equivalent of PI: 3.14 etc. |
| SQRT1_2 | The square root of one-half |
| SQRT2 | The square root of 2 |
| abs | Returns the absolute value of a number |
| acos | Returns the arc cosine of a number |
| asin | Returns the arc sine of a number |
| atan | Returns the arc tangent of a number |
| ceil | Returns the least integer greater than or equal to a number |
| cos | Returns the cosine of a number |
| exp | Returns e (Euler's constant) to the power of a number |
| floor | Returns the greatest integer less than or equal to its argument |
| log | Returns the natural logarithm (base e) of a number |
| max | Returns the greater of two values |
| min | Returns the lesser of two values |
| pow | Returns the value of a number times a specified power |
| random | Returns a random number (X-platforms only) |
| round | Returns a number rounded to the nearest whole value |
| sin | Returns the sine of a number |
| sqrt | Returns the square root of a number |
| tan | Returns the tangent of a number |
JavaScript treats the Date object like a constructor class. To use Date you must create a new Date object; you can then apply
the various Date methods to get and set dates. (The Date object has no properties.) If you're familiar with the Date class
in Java, you'll find the properties of the JavaScript Date object largely the same. The most commonly used methods are the
get methods, which obtain the time and date of the value in the Date object. These methods are: