JavaScript cos

The JavaScript cos function is a Math function that calculates the trigonometric cosine for the specified expression. The cos function returns the value between -1 and 1, and its syntax is

Math.cos(number);

The mathematical formula of the JS Trigonometry Cosine function is the Length of the Adjacent Side / Length of the Hypotenuse.

JavaScript cos example

In this example, we will find the Cosine values of different data types and display the output. Please refer to the acos Function to know the JScript Arc Cosine.

TIP: Please refer to the cosh() and acosh() functions in a Math article for the hyperbolic arc cosine values.

<!DOCTYPE html>
<html>
<head>
    <title> JavaScriptCOSFunction </title>
</head>
<body>
  <h1> JavaScriptCOSFunction </h1>
  <p id = "Pos"></p>
  <p id = "Neg"></p>
  <p id = "Dec"></p>
  <p id = "Neg_Dec"></p>
  <p id = "Str"></p>
  <p id = "Exp"></p>
  <p id = "Null"></p>
  <p id = "Multi"></p>
  <script>
    document.getElementById("Pos").innerHTML = Math.cos(20);
    document.getElementById("Neg").innerHTML = Math.cos(-10);
    document.getElementById("Dec").innerHTML = Math.cos(40.45);
    document.getElementById("Neg_Dec").innerHTML = Math.cos(-60.75);
    document.getElementById("Str").innerHTML = Math.cos("JavaScript");
    document.getElementById("Null").innerHTML = Math.cos(null);
    document.getElementById("Multi").innerHTML = Math.cos(0.25 + 0.55 - 0.77);
  </script>
</body>
</html>
JavaScript cos Function Example

Example 2: If we pass positive or negative infinity values or a NaN value, the cos() function returns NaN as output.

let a = Infinity;
let b = -Infinity;
let c = NaN;
console.log(Math.cos(a));
console.log(Math.cos(b));
console.log(Math.cos(c));
NaN 
NaN 
NaN

Example 3: When we use the cos() function on positive and negative 0’s, it returns the positive 1 as output.

console.log(Math.cos(0));
console.log(Math.cos(-0));
1 
1

JavaScript math cos degrees

By default, the cos() function finds the cosine value of radians. However, to find the cosine value of a given degree, we must convert given degrees to radians and apply the cos() function to it.

function calCDg(degrees) {
return Math.cos(degrees * Math.PI / 180);
}

console.log(calCDg(0));
console.log(calCDg(30));
console.log(calCDg(60));
console.log(calCDg(90));
1 
0.8660254037844387 
0.5000000000000001 
6.123233995736766e-17