Open In App

What is Math in JavaScript?

Last Updated : 24 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript provides a built-in Math object that provides a set of methods to perform mathematical operations. These operations range from basic to more complex functions like trigonometry and logarithms. The Math object allows you to perform calculations without the need for writing custom functions.

Syntax:

Math.methodName(argument1, argument2, ...);

The Math object in JavaScript provides a variety of methods to perform various mathematical operations, some of the Math object methods are listed below:

Example 1: This example is demonstrating using of Math object methods to perform trigonometry, exponents, and logarithms operations.

Javascript




let x = 10;
 
// Trigonometry
let angleInRadians = Math.PI / 4; // 45 degrees
 
let sineValue = Math.sin(angleInRadians);
let cosineValue = Math.cos(angleInRadians);
let tangentValue = Math.tan(angleInRadians);
 
console.log("Sine:", sineValue);
console.log("Cosine:", cosineValue);
console.log("Tangent:", tangentValue);
 
// Exponents and Logarithms
let base = 2;
let exponent = 3;
 
let powerResult = Math.pow(base, exponent);
let squareRootResult = Math.sqrt(x);
let logarithmResult = Math.log(x);
let exponentialResult = Math.exp(x);
 
console.log("Power:", powerResult);
console.log("Square Root:", squareRootResult);
console.log("Natural Logarithm:", logarithmResult);
console.log("Exponential:", exponentialResult);


Output

Sine: 0.7071067811865475
Cosine: 0.7071067811865476
Tangent: 0.9999999999999999
Power: 8
Square Root: 3.1622776601683795
Natural Logarithm: 2.302585092994046
Exponential: 22026.465794806718

Example 2: This example is demonstrating using of Math object method Math.random() to generate random number between 1 to 100.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        Random Number Generator
    </title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
    </style>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <h2>
        Random Number Generator
    </h2>
 
    <p>
        Click the button to generate a
        random number between 1 to 100:
    </p>
 
    <button onclick="generateRandomNumber()">
        Generate Random Number
    </button>
 
    <p id="randomNumber"></p>
 
    <script>
        const generateRandomNumber = () => {
            let randomNumber =
            Math.floor(Math.random() * 100) + 1;
            document.getElementById("randomNumber").
            innerText = `Random Number: ${randomNumber}`;
        }
    </script>
 
</body>
 
</html>


Output:

mathGIF



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads