# How to Use the Math.tan() Method in JavaScript

09/30/2021

Contents

In this article, you will learn how to use the Math.tan() method in JavaScript.

## Using the Math.tan() method in JavaScript

The Math.tan() method is a built-in function in JavaScript that returns the tangent value of a given angle in radians.

### Syntax

``Math.tan(x)``

### Parameters

x: A number representing an angle in radians.

### Return Value

A number representing the tangent value of the given angle.

### Examples

To calculate the tangent value of an angle in JavaScript, we can use the Math.tan() method as follows:

``````let angle = 45; // angle in degrees
let radians = angle * Math.PI / 180; // convert degrees to radians
let tangentValue = Math.tan(radians); // calculate the tangent value
console.log(tangentValue); // output: 1
``````

In this example, we first define an angle of 45 degrees. To calculate the tangent value of this angle, we need to convert it into radians. We do this by multiplying the angle by Math.PI / 180. The result is then passed as an argument to the Math.tan() method, which calculates the tangent value of the angle. The result is stored in the tangentValue variable and then output to the console.

We can also use the Math.tan() method to create a tangent line in JavaScript. To do this, we need to plot the tangent values of different angles over time. Here’s an example:

``````let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
let x = 0;
let y = canvas.height / 2;
ctx.beginPath();
ctx.moveTo(x, y);
for (let i = 0; i < canvas.width; i++) {
let angle = i * Math.PI / 180;
let tangentValue = Math.tan(angle);
y = canvas.height / 2 + tangentValue * 50;
ctx.lineTo(i, y);
}
ctx.stroke();
``````

In this example, we first define a canvas element and get its context using the getContext() method. We also define the initial values of x and y, which represent the starting point of the tangent line. We then call the beginPath() method to start drawing on the canvas.

Inside the for loop, we calculate the tangent value of each angle and store it in the tangentValue variable. We then update the value of y by adding the tangent value multiplied by 50 to the canvas height divided by 2. Finally, we draw a line from the previous point to the new point using the lineTo() method.

When we call the stroke() method, the tangent line will be drawn on the canvas.