(click anywhere to close)

# [JavaScript] Math

category: Website | course: JavaScript | difficulty:

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 `Math.abs(x)` Absolute value of x `Math.round(x)` Rounds x to the nearest integer `Math.floor(x)` Rounds x down to the nearest integer `Math.ceil(x)` 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 `Math.max(x1,x2,…,xn)` Maximum; returns number with highest value `Math.min(x1,x2,…,xn)` Minimum; returns number with lowest value `Math.random()` Random number between 0 and 1 `Math.pow(x,y)` x to the power of y `Math.exp(x)` Returns the value of Ex `Math.log(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 `Math.sin(x)` Sine of x `Math.cos(x)` Cosine of x `Math.tan(x)` Tangent of x `Math.asin(x)` Arcsine of x `Math.acos(x)` Arccosine of x `Math.atan(x)` Arctangent of x, as numeric value between –PI/2 and PI/2 radians `Math.atan2(x,y)` Arctangent of the quotient of its arguments `Math.sqrt(x)` 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 `Math.E` Euler’s number `Math.PI` PI (π) `Math.SQRT2` Square root of 2 `Math.SQRT1_2` Square root of 1/2 `Math.LN2` Natural logarithm of 2 `Math.LN10` Natural logarithm of 10 `Math.LOG2E` Base 2 logarithm of Euler’s number `Math.LOG10E` Base 10 logarithm of Euler’s number
```console.log(Math.PI); //Prints 3.141592653589793
```
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)