[JavaScript] Math
category: Website  course: JavaScript  difficulty:QUICK CONTENTS:
1. How to Use It
2. Manipulating Numbers
3. Finding Values
4. Trigonometry
5. Constants
To finish the part on Numbers, let’s have a look at the Math object. It has a great deal of useful methods, like the sine and cosine functions, as well as important mathematical constants.
How to Use It
Calling it is as simple as writing Math.someMethod(arguments)
The Math object is created and maintained by JavaScript itself, which means you don’t have to declare it, and it can be accessed from anywhere. Calling such a method doesn’t change the actual number(s) you put into it; it simply generates a number using them, and gives it to you to do whatever you want with it.
var x = 0; var y = Math.cos(x); // y is 1, but x is still zero
Manipulating Numbers
Method 
Description 

Absolute value of x 

Rounds x to the nearest integer 

Rounds x down to the nearest integer 

Rounds x up to the nearest integer 
console.log(Math.floor(1.5)); //Prints 1 console.log(Math.ceil(1.5)); //Prints 2 console.log(Math.round(1.5)); //Prints 2
Finding Values
Method 
Description 

Maximum; returns number with highest value 

Minimum; returns number with lowest value 

Random number between 0 and 1 

x to the power of y 

Returns the value of E^{x} 

Returns the value of ln(x) 
console.log(Math.min(1,5,3,10,50)); //Prints 5
Math.random()
generates a random number between 0 (inclusive) and 1 (exclusive). If you, for example, want a random value between 0 and 100, simply multiply this value by one hundred.
Trigonometry
Method 
Description 

Sine of x 

Cosine of x 

Tangent of x 

Arcsine of x 

Arccosine of x 

Arctangent of x, as numeric value between –PI/2 and PI/2 radians 

Arctangent of the quotient of its arguments 

Square root of x 
var x = Math.sin(0) + Math.cos(0) + Math.sqrt(4); // x is 3
JavaScript works with radians, not degrees!
Constants
Method 
Description 

Euler’s number 

PI (π) 

Square root of 2 

Square root of 1/2 

Natural logarithm of 2 

Natural logarithm of 10 

Base 2 logarithm of Euler’s number 

Base 10 logarithm of Euler’s number 
console.log(Math.PI); //Prints 3.141592653589793