JS Math Function

HTML
CSS
C#
SQL

Math Function

The Math Function in JavaScript provides a set of built-in mathematical functions and constants. These functions allow you to perform various mathematical operations in your JavaScript code.

Here are some of the Match functions commonly used methods:

1. Basic Math Operations:

The Math Function doesn’t have direct methods for addition, subtraction, multiplication, or division. Instead, these operations are typically performed using the standard operators (+, -, *, /).

Example:

2. Rounding:

The Math.round, Math.floor, and Math.ceil functions are used for rounding numbers.

Example:

3. Exponents and Logarithms:

The Math.pow function is used for exponentiation.

Example:

     let base = 2;
     let exponent = 3;

     let result = Math.pow(base, exponent); // Calculates 2^3 = 8

    document.write (“Result:”, result);

4. Square Root:

The Math.sqrt function is used for finding the square root of a number.

Example:

     let number = 25;
     let sqrt = Math.sqrt(number); // Calculates the square root of 25

    document.write (“Square Root:”, sqrt);

5. Trigonometry:

The Math.sin, Math.cos, and Math.tan functions are used for trigonometric calculations.

Example:

     let angleInRadians = Math.PI / 4; // 45 degrees in radians
     let sineValue = Math.sin(angleInRadians);
     let cosineValue = Math.cos(angleInRadians);
     let tangentValue = Math.tan(angleInRadians);
    document.write (“Sine:”, sineValue, “Cosine:”, cosineValue, “Tangent:”, tangentValue);

6. Random Number Generation:

The Math.random function generates a random floating-point number between 0 (inclusive) and 1 (exclusive).

Example:

     let randomNum = Math.random(); // Generates a random number between 0 (inclusive) and 1 (exclusive)
    document.write (“Random Number:”, randomNum);

7. Constants:

The Math.PI and Math.E constants represent the mathematical constants π (pi) and e.

Example:

let piValue = Math.PI; // 3.141592653589793
    let eValue = Math.E;   // 2.718281828459045
    document.write (“Pi:”, piValue, “E:”, eValue);

These examples cover some of the commonly used methods provided by the Math Function in JavaScript. The Math Function is static, so you don’t need to create an instance of it. The methods are directly accessed using the Math prefix.

Here are List of Math Function

 Function
Description
Example

Math.abs(x)

Returns the absolute value of a number (i.e., the distance from zero)

Math.abs(-5) returns 5

Math.ceil(x)

Returns the smallest integer greater than or equal to a number

Math.ceil(3.14) returns 4

Math.floor(x)

Returns the largest integer less than or equal to a number

Math.floor(3.14) returns 3

Math.max(x, y, z, …)

Returns the highest value among the given arguments

Math.max(2, 4, 6, 8) returns 8

Math.min(x, y, z, …)

Returns the lowest value among the given arguments

Math.min(2, 4, 6, 8) returns 2

Math.pow(x, y)

Returns the result of raising a number to a power

Math.pow(2, 3) returns 8

 

Math.random()

Returns a random number between 0 and 1 (exclusive)

Math.random() returns a value between 0 and 1 (e.g., 0.5)

Math.round(x)

Returns the value of a number rounded to the nearest integer

Math.round(3.14) returns 3

Math.sqrt(x)

Returns the square root of a number

Math.sqrt(16) returns 4

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a function generateRandomNumber that generates a random integer between 1 and 100 (inclusive) and returns it.

The function uses Math.random() to generate a decimal between 0 and 1, multiplies it by 100 to get a range from 0 to 100, and then rounds down to the nearest whole number using Math.floor().

Here’s an example program:

function generateRandomNumber() {
return Math.floor(Math.random() * 100) + 1;
}

let randomNum = generateRandomNumber();
console.log(randomNum); // Example output: 42

Output

2. Create a function calculateAreaOfCircle that takes the radius of a circle as a parameter and returns the area.

The function uses the formula for the area of a circle, Math.PI * radius^2, where Math.PI gives the value of π.

Here’s an example program:

function calculateAreaOfCircle(radius) {
return Math.PI * Math.pow(radius, 2);
}

let radius = 5;
let area = calculateAreaOfCircle(radius);
console.log(area); // Example output: 78.54

Output

3. Write a function roundToNearestWhole that takes a decimal number as a parameter and rounds it to the nearest whole number.

The function uses Math.round() to round the decimal number to the nearest whole number.

Here’s an example program:

function roundToNearestWhole(number) {
return Math.round(number);
}

let decimalNumber = 7.89;
let roundedNumber = roundToNearestWhole(decimalNumber);
console.log(roundedNumber); // Example output: 8

Output

4. Create a function calculateHypotenuse that takes the lengths of two sides of a right-angled triangle as parameters and returns the length of the hypotenuse.

The function uses the Pythagorean theorem to calculate the hypotenuse: Math.sqrt(side1^2 + side2^2).

Here’s an example program:

function calculateHypotenuse(side1, side2) {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}

let side1 = 3;
let side2 = 4;
let hypotenuse = calculateHypotenuse(side1, side2);
console.log(hypotenuse); // Example output: 5

Output

5) Age Calculator: Build a simple age calculator using JavaScript. Ask the user to input their date of birth, and then calculate and display their age in years, months, and days. Ensure that the displayed age updates dynamically as time passes.

The “Age Calculator” program in JavaScript is a simple application that asks the user to input their date of birth. The program then calculates and displays the user’s age in years, months, and days. The displayed age updates dynamically as time passes.
1. User Input: The program prompts the user to enter their date of birth. The input can be in any standard date format.
2. Calculate Age: Using the current date and the entered date of birth, the program calculates the user’s age in years, months, and days.
3. Dynamic Display: The calculated age is displayed on the webpage, and this display updates dynamically as time passes. This means that if the user leaves the page open, the age will automatically adjust based on the current date.

Here’s an example program:

<body>

<h2>Age Calculator</h2>

<label for=”dob”>Enter your Date of Birth:</label>
<input type=”date” id=”dob” onchange=”calculateAge()”>

<p id=”result”></p>

<script>
function calculateAge() {
// Get the user’s date of birth from the input
var dob = new Date(document.getElementById(“dob”).value);

// Get the current date
var currentDate = new Date();

// Calculate the difference in milliseconds
var ageInMilliseconds = currentDate – dob;

// Convert milliseconds to years, months, and days
var ageInYears = Math.floor(ageInMilliseconds / (365.25 * 24 * 60 * 60 * 1000));
var ageInMonths = Math.floor(ageInMilliseconds / (30.44 * 24 * 60 * 60 * 1000));
var ageInDays = Math.floor(ageInMilliseconds / (24 * 60 * 60 * 1000));

// Display the calculated age
document.getElementById(“result”).textContent = “Your age is: ” +
ageInYears + ” years, ” +
ageInMonths + ” months, and ” +
ageInDays + ” days.”;
}
</script>

</body>

Output

6) Countdown Timer: Create a countdown timer using JavaScript. Allow the user to input a future date and time, and then display a countdown on the web page until that specified date and time is reached. Update the countdown in real time.

The “Countdown Timer” program in JavaScript is a simple application that allows the user to input a future date and time. The program then displays a countdown on the webpage, showing the time remaining until the specified date and time is reached. The countdown updates in real-time.
1. User Input: The program prompts the user to input a future date and time. The user can enter the date and time in any valid format.
2. Calculate Countdown: Using the current date and time along with the user-input future date and time, the program calculates the remaining time until the specified date and time is reached.
3. Real-Time Update: The calculated countdown is displayed on the webpage, and this displays updates in real-time. As time passes, the countdown dynamically adjusts to show the updated time remaining.

Here’s an example program:

<body>

<h2>Countdown Timer</h2>

<label for=”futureDate”>Enter Future Date and Time:</label>
<input type=”datetime-local” id=”futureDate” onchange=”startCountdown()”>

<p id=”countdown”></p>

<script>
function startCountdown() {
// Get the user’s input for the future date and time
var futureDate = new Date(document.getElementById(“futureDate”).value);

// Update the countdown every second
var countdownInterval = setInterval(function() {
// Get the current date and time
var currentDate = new Date();

// Calculate the time remaining
var timeRemaining = futureDate – currentDate;

// Check if the countdown has reached zero
if (timeRemaining <= 0) {
// Display a message when the countdown reaches zero
document.getElementById(“countdown”).textContent = “Countdown Expired!”;
// Stop the interval to avoid negative values
clearInterval(countdownInterval);
} else {
// Convert milliseconds to hours, minutes, and seconds
var hours = Math.floor(timeRemaining / (1000 * 60 * 60));
var minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

// Display the countdown in real time
document.getElementById(“countdown”).textContent =
“Time Remaining: ” + hours + “h ” + minutes + “m ” + seconds + “s”;
}
}, 1000); // Update every second
}

</script>

</body>

Output