JavaScript Math tan()

The JavaScript Math.tan() function returns the tangent of a specified number.

The syntax of the Math.tan() function is:

Math.tan(x)

tan(), being a static method, is called using the Math class name.


Math.tan() Parameters

The Math.tan() function takes in:

  • x - A number (in radians) whose tangent value is required.

Return value from Math.tan()

  • Returns the tangent of a given angle (in radians).

Example 1: Using Math.tan()

// tangent of 1 radian
var value1 = Math.tan(1);
console.log(value1); // Output: 1.5574077246549023

// negative radians are allowed
var value2 = Math.tan(-2);
console.log(value2); // Output: 2.185039863261519

// Math constants can be used
var value3 = Math.cos(Math.PI);
console.log(value3); // Output: -1

Output

1.5574077246549023
2.185039863261519
-1

Example 2: Using Math.tan() with degrees

// custom function for angle in degrees
function tan(degrees) {
  var radians = (degrees * Math.PI) / 180;
  return Math.tan(radians);
}

// tangent of 57 degrees
value1 = tan(57);
console.log(value1); // Output: 1.5398649638145825

value2 = tan(0);
console.log(value2); // Output: 0

value3 = tan(45);
console.log(value3); // Output: 0.9999999999999999

Output

1.5398649638145825
0
0.9999999999999999

In the example above, we have defined a function that converts the degree value to radian and then passes it to Math.tan().

Here, tan(45) gives 0.99999999999999 instead of 1 because floats are not stored perfectly in memory.

We can define custom functions in similar ways to extend the capabilities of such built-in functions.


Recommended readings: