The cos method in JavaScript is utilized to calculate the cosine of a specified number. The output generated by the cos method falls within the range of -1 to 1, reflecting the cosine value of the angle provided.
Syntax
The syntax for the cos method is expressed as follows:
Math.cos(num)
Parameter
num - A number.
Return
The cosine of a number.
JavaScript Math cos method example
In this section, we will explore the cos function by examining several examples.
Example 1
Let's see a simple example of cos method.
<script>
document.writeln(Math.cos(1)+"<br>");
document.writeln(Math.cos(2));
</script>
Output:
0.5403023058681398
-0.4161468365471424
Example 2
In this demonstration, we will employ the cos function utilizing negative values.
<script>
document.writeln(Math.cos(-1)+"<br>");
document.writeln(Math.cos(-0.5));
</script>
Output:
0.5403023058681398
0.8775825618903728
Example 3
Let’s examine the cos function using a variety of test scenarios.
<script>
document.writeln(Math.cos(0)+"<br>");
document.writeln(Math.cos(Math.PI));
</script>
Output:
Example 4
In this section, you have the opportunity to evaluate the cos function utilizing your own set of test cases.
<script>
function display()
{
var x=document.getElementById("num").value;
document.getElementById("result").innerHTML=Math.cos(x);
}
</script>
<form>
Enter a number: <input type="text" id="num">
<input type="button" onclick="display()" value="submit">
</form>
<p><span id="result"></span></p>