Math
9 methodsBuilt-in object with mathematical constants and functions.
Math.max(...values)Return the largest of zero or more numbers. Returns -Infinity with no args.
Parameters
| Name | Type | Description |
|---|---|---|
| values | ...number | Numbers to compare. |
Returns
number
Example
javascript
Math.max(1, 2, 3) // 3
Math.max(...[1, 2, 3]) // 3
Math.max() // -InfinityMath.min(...values)Return the smallest of zero or more numbers. Returns Infinity with no args.
Parameters
| Name | Type | Description |
|---|---|---|
| values | ...number | Numbers to compare. |
Returns
number
Example
javascript
Math.min(1, 2, 3) // 1
Math.min(...[1, 2, 3]) // 1
Math.min() // InfinityMath.round(x)Return the value of x rounded to the nearest integer.
Parameters
| Name | Type | Description |
|---|---|---|
| x | number | Number to round. |
Returns
number
Example
javascript
Math.round(2.4) // 2
Math.round(2.5) // 3
Math.round(-2.5) // -2 (rounds toward +Infinity)Math.floor(x)Return the largest integer less than or equal to x.
Parameters
| Name | Type | Description |
|---|---|---|
| x | number | Number to floor. |
Returns
number
Example
javascript
Math.floor(2.7) // 2
Math.floor(-2.3) // -3Math.ceil(x)Return the smallest integer greater than or equal to x.
Parameters
| Name | Type | Description |
|---|---|---|
| x | number | Number to ceil. |
Returns
number
Example
javascript
Math.ceil(2.1) // 3
Math.ceil(-2.9) // -2Math.abs(x)Return the absolute value of x.
Parameters
| Name | Type | Description |
|---|---|---|
| x | number | Number. |
Returns
number
Example
javascript
Math.abs(-5) // 5
Math.abs(3.14) // 3.14
Math.abs(-7.5) // 7.5Math.pow(base, exponent)Return base raised to the exponent power (equivalent to base ** exponent).
Parameters
| Name | Type | Description |
|---|---|---|
| base | number | Base. |
| exponent | number | Exponent. |
Returns
number
Example
javascript
Math.pow(2, 10) // 1024
Math.pow(9, 0.5) // 3
2 ** 10 // 1024Math.sqrt(x)Return the positive square root of x. Returns NaN if x < 0.
Parameters
| Name | Type | Description |
|---|---|---|
| x | number | Non-negative number. |
Returns
number
Example
javascript
Math.sqrt(9) // 3
Math.sqrt(2) // 1.4142135623730951
Math.sqrt(-1) // NaNMath.random()Return a pseudo-random number in [0, 1).
Returns
number
Example
javascript
Math.random() // e.g. 0.4246...
Math.floor(Math.random() * 10) // 0..9
Math.floor(Math.random() * 6) + 1 // 1..6 (dice)