Math Object in JavaScript
In our previous tutorial, we created a simple calculator using JavaScript. In this tutorial, you will learn advanced Math functions to perform scientific operations of the calculator using JavaScript. To perform mathematical tasks on web pages, we use JavaScript Math object. This object allows us to perform different mathematical work and calculation by using just one simple function.
Math Functions
In JavaScript there are sevral mathematical function some are given below:
- Random()
- Max()
- Min()
- Floor()
- Round()
- Abs()
- Log()
- Cos()
- Sin()
- Tan()
- Sqrt()
Math.random()
This function returns 1 or 0 randomly.
1 2 3 4 |
<script> var x=Math.random(); alert(x); </script> |
Result
1 |
0.4105918002502311 |
Math.Max()
This function returns maximum value from its given parameters.
1 2 3 4 5 6 |
<script> var x=Math.max(0, 150, 30, 20, -8, -200); alert(x); </script> |
Result
1 |
150 |
Math.Min()
This function returns minimum value from its given parameters.
1 2 3 4 5 6 |
<script> var x=Math.min(0, 150, 30, 20, -8, -200); alert(x); </script> |
Result
1 |
-200 |
Math.floor()
This function rounds a number down to the nearest integer.
1 2 3 4 5 6 |
<script> var x=Math.floor(4.7); alert(x); </script> |
Result
1 |
4 |
Math.Round()
This function rounds a number to the nearest integer.
1 2 3 4 5 6 |
<script> var x=Math.round(4.7); alert(x); </script> |
Result
1 |
5 |
Math.ceil()
This function rounds a number up to the nearest integer.
1 2 3 4 5 6 |
<script> var x=Math.ceil(4.7); alert(x); </script> |
Result
1 |
5 |
Math.Abs()
This function returns the absolute value of given parameter.
1 2 3 4 5 6 |
<script> var x=Math.abs(4); alert(x); </script> |
Result
1 |
4 |
Math.log()
This function returns the log of the given parameter.
1 2 3 4 5 6 |
<script> var x=Math.log(29); alert(x); </script> |
Result
1 |
3.367295829986474 |
Math.tan()
This function returns the tangent of the given parameter.
1 2 3 4 5 6 |
<script> var x=Math.tan(7); alert(x); </script> |
Result
1 |
0.8714479827243187 |
Math.sin()
This function returns the sin of the given parameter.
1 2 3 4 5 6 |
<script> var x=Math.sin(4); alert(x); </script> |
Result
1 |
-0.7568024953079282 |
Math.cos()
This function returns the cos of the given parameter.
1 2 3 4 5 6 |
<script> var x=Math.cos(7); alert(x); </script> |
Result
1 |
0.7539022543433046 |
Math.sqrt()
This function returns the square of the given parameter.
1 2 3 4 5 6 |
<script> var x=Math.sqrt(45); alert(x); </script> |
Result
1 |
6.708203932499369 |