JavaScript Math.cos() Method
The JavaScript Math.cos() method accepts a numeric value (angle in radians) as a parameter and calculates the trigonometric cosine of the specified angle and returns it.
This method returns the cosine of specified angle in between "-1" and "1", inclusive. If the angle is "Infinity", "-Infinity", or "NaN", this method returns NaN as output.
Syntax
Following is the syntax of JavaScript Math.cos() method −
Math.cos(x);
Parameters
This method accepts only one parameter. The same is described below −
- x: A numeric value representing an angle in radians.
Return value
This method returns the cosine value of the specified angle (x).
Example 1
In the following example, we are calculating the cosine value of the angle "5" using the JavaScript Math.cos() method −
<html> <body> <script> let number = Math.cos(5); document.write(number); </script> </body> </html>
Output
After executing the above program, it returns "0.28366218546322625" as result.
Example 2
Here, we are computing the cosine value of the angle "0" −
<html> <body> <script> let number = Math.cos(0); document.write(number); </script> </body> </html>
Output
It returns "1" as result.
Example 3
In this example, we are passing a mathematic constant PI (3.14) as a parameter to this method −
<html> <body> <script> let number = Math.cos(Math.PI); document.write(number); </script> </body> </html>
Output
The above program computes the cosine of PI and returns "-1" as result.
Example 4
The cosine of an infinite angle will be indefinite, that can't be defined with a number, so it returns "NaN" as result −
<html> <body> <script> let number1 = Math.cos(-Infinity); let number2 = Math.cos(Infinity); document.write(number1, "<br>", number2); </script> </body> </html>
Output
It returns NaN as result.
Example 5
If we try to calculate the cosine value of a non-numeric value or empty number, it returns NaN as result −
<html>
<body>
<script>
let value1 = Math.cos("Tutorialspoint");
let value2 = Math.cos();
document.write(value1, "<br>", value2);
</script>
</body>
</html>
Output
As we can see in the output, the above program returned NaN.