Math Function
In JavaScript, the Math object is a built-in object that provides a set of mathematical functions and constants to help you perform common mathematical operations. You don’t need to create an instance of it (no need to new Math()), you can directly use its methods.
Key Features of the Math Object:
1. Static Methods: These methods are available directly from the Math object and help you perform tasks like finding square roots, rounding numbers, or determining a number’s absolute value.
2. Mathematical Constants: The Math object provides constants like π (Pi) and e (Euler’s number) for calculations.
Common Methods of the Math Object:
Methods | Description |
---|---|
Math.round() | Rounds a number to the nearest integer. |
Math.floor() | Rounds a number to the nearest integer. |
Math.ceil() | Rounds a number up to the nearest integer. |
Math.abs() | Returns the absolute value (positive value) of a number. |
Math.sqrt() | Returns the square root of a number. |
Math.min() | Finds the smaller of two numbers. |
Math.max() | Finds the larger of two numbers. |
Math.pow() | Calculates a number raised to a power. |
Math.random() | Generates a random number between 0 (inclusive) and 1 (exclusive). |
Math.trunc() | Removes the decimal part of a number, keeping only the integer part. |
Examples of Common Methods:
Math.round()
//Math.round() – Rounds a number to the nearest integer.
let number = 4.6;
let roundedNumber = Math.round(number);
console.log(roundedNumber); // Output: 5
Code explanation:
let number = 4.6;
This line declares a variable called number and assigns it the value 4.6.
let roundedNumber = Math.round(number);
The Math.round() function rounds the value of number (which is 4.6) to the nearest integer.
Math.round(4.6) rounds 4.6 up to 5 because 4.6 is closer to 5 than to 4.
The result is stored in the variable roundedNumber.
console.log(roundedNumber);
This line prints the value of roundedNumber (which is 5) to the console.
Output:
Math.floor()
//Math.floor() – Rounds a number down to the nearest integer.
let number = 4.9;
let flooredNumber = Math.floor(number);
console.log(flooredNumber); // Output: 4
Code explanation:
let number = 4.9;
This line declares a variable called number and assigns it the value 4.9.
let flooredNumber = Math.floor(number);
The Math.floor() function rounds the value of number (which is 4.9) down to the nearest integer.
Math.floor(4.9) rounds 4.9 down to 4, regardless of how close the number is to the next whole number.
The result is stored in the variable flooredNumber.
console.log(flooredNumber);
This line prints the value of flooredNumber (which is 4) to the console.
Output:
Math.ceil()
//Math.ceil() – Rounds a number up to the nearest integer.
let number = 4.1;
let ceiledNumber = Math.ceil(number);
console.log(ceiledNumber); // Output: 5
Code explanation:
let number = 4.1;
This line declares a variable called a number and assigns it the value 4.1.
let ceiledNumber = Math.ceil(number);
The Math.ceil() function rounds the value of the number (which is 4.1) up to the nearest integer.
Math.ceil(4.1) rounds 4.1 up to 5, even though 4.1 is closer to 4.
The result is stored in the variable ceiledNumber.
console.log(ceiledNumber);
This line prints the value of ceiledNumber (which is 5) to the console.
Output:
Math.abs()
Math.abs() – Returns the absolute (positive) value of a number.
let negativeNumber = -8;
let absoluteValue = Math.abs(negativeNumber);
console.log(absoluteValue); // Output: 8
Code explanation:
let negativeNumber = -8;
This line declares a variable called negativeNumber and assigns it the value -8.
let absoluteValue = Math.abs(negativeNumber);
The Math.abs() function returns the absolute value of the number passed to it.
The absolute value of a number is its distance from zero, always expressed as a positive number.
Math.abs(-8) returns 8, because the absolute value of -8 is 8.
The result is stored in the variable absoluteValue.
console.log(absoluteValue);
This line prints the value of absoluteValue (which is 8) to the console.
Output:
Math.sqrt()
//Math.sqrt() – Calculates the square root of a number.
let number = 16;
let squareRoot = Math.sqrt(number);
console.log(squareRoot); // Output: 4
Code explanation:
let number = 16;
This line declares a variable called number and assigns it the value 16.
let squareRoot = Math.sqrt(number);
The Math.sqrt() function calculates the square root of the number passed to it.
Math.sqrt(16) returns 4, because 4 × 4 = 16.
The result is stored in the variable squareRoot.
console.log(squareRoot);
This line prints the value of squareRoot (which is 4) to the console.
Output:
Math.min()
//Math.min() – Returns the smaller of two numbers.
let number1 = 10;
let number2 = 20;
let smaller = Math.min(number1, number2);
console.log(smaller); // Output: 10
Code explanation:
let number1 = 10;
This line declares a variable called number1 and assigns it the value 10.
let number2 = 20;
This line declares a variable called number2 and assigns it the value 20.
let smaller = Math.min(number1, number2);
The Math.min() function returns the smallest value among the numbers passed to it.
Math.min(10, 20) returns 10, because 10 is smaller than 20.
The result is stored in the variable smaller
console.log(smaller);
This line prints the value of smaller (which is 10) to the console.
Output:
Math.max()
//Math.max() – Returns the larger of two numbers.
let number1 = 10;
let number2 = 20;
let larger = Math.max(number1, number2);
console.log(larger); // Output: 20
Code explanation:
let number1 = 10;
This line declares a variable called number1 and assigns it the value 10.
let number2 = 20;
This line declares a variable called number2 and assigns it the value 20.
let larger = Math.max(number1, number2);
The Math.max() function returns the largest value among the numbers passed to it.
Math.max(10, 20) returns 20, because 20 is larger than 10.
The result is stored in the variable larger.
console.log(larger);
This line prints the value of larger (which is 20) to the console.
Output:
Math.pow()
//Math.pow() – Raises a number to the power of another number.
let base = 2;
let exponent = 3;
let result = Math.pow(base, exponent);
console.log(result); // Output: 8
Code explanation:
let base = 2;
This line declares a variable called base and assigns it the value 2.
let exponent = 3;
This line declares a variable called exponent and assigns it the value 3.
let result = Math.pow(base, exponent);
The Math.pow() function calculates base raised to the power of exponent.
Math.pow(2, 3) calculates 2^3, which is 2 × 2 × 2 = 8.
The result is stored in the variable result.
console.log(result);
This line prints the value of result (which is 8) to the console.
Output:
Math.random()
//Math.random() – Generates a random number between 0 (inclusive) and 1 (exclusive).
let randomNumber = Math.random();
console.log(randomNumber); // Output: A random number like 0.844
Code explanation:
let randomNumber = Math.random();
The Math.random() function generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
The number generated will be greater than or equal to 0 but less than 1.
Example output could be 0.234, 0.844, 0.557, etc.
console.log(randomNumber);
This line prints the randomly generated number to the console.
Output:
Math.trunc()
//Math.trunc() – Removes the decimal part of a number.
let number = 7.9;
let truncated = Math.trunc(number);
console.log(truncated); // Output: 7
Code explanation:
let number = 7.9;
This line declares a variable called number and assigns it the value 7.9.
let truncated = Math.trunc(number);
The Math.trunc() function removes the fractional (decimal) part of the number and returns the integer part.
Math.trunc(7.9) removes the decimal part (0.9), resulting in 7.
The result is stored in the variable truncated.
console.log(truncated);
This line prints the value of truncated (which is 7) to the console.
Output:
Mathematical Constants:
Math.PI
//Math.PI: The value of π (pi), approximately 3.14159.
console.log(Math.PI); // Output: 3.141592653589793
Math.PI is a built-in constant in JavaScript that represents the mathematical value of π (pi), approximately 3.14159.
The console.log() function is used to print the value of Math.PI to the console.
Output:
Math.E:
//Math.E: The value of e (Euler’s number), approximately 2.71828.
console.log(Math.E); // Output: 2.718281828459045
Math.E is a built-in constant in JavaScript that represents the mathematical constant e, approximately 2.71828.
The console.log() function prints the value of Math.E to the console.
Output:
The Math object in JavaScript makes it easy to work with numbers and perform complex mathematical calculations. Whether you’re rounding numbers, calculating square roots, or generating random values, the Math object has you covered!
Course Video
Practice Scenario
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:
The Math object provides built-in mathematical constants and functions for performing calculations, such as rounding, trigonometry, and exponentiation. Learn more in our JavaScript math function free course video.
Use Math.round() to round to the nearest integer.
Example:
console.log(Math.round(4.5)); // Output: 5
Discover how to use this in the JS math function with free video tutorial.
- Math.floor(): Rounds a number down to the nearest integer.
- Math.ceil(): Rounds a number up to the nearest integer.
Check out practical examples in the Free JavaScript math function tutorial for beginners.
Use Math.random() to generate a random number between 0 (inclusive) and 1 (exclusive).
Example:
console.log(Math.random());
Learn this technique in the JavaScript math functions with free tutorial.
Yes, multiply Math.random() by the range and add the start value.
Example:
function getRandom(min, max) {
return Math.floor(Math.random() * (max – min + 1)) + min;
}
Find step-by-step instructions in the JavaScript math function free course video.
Use Math.sqrt().
Example:
console.log(Math.sqrt(16)); // Output: 4
Explore this in the JS math function with free video tutorial.
The Math.pow() method calculates the power of a number.
Example:
console.log(Math.pow(2, 3)); // Output: 8
Learn how this works in the Free JavaScript math function tutorial for beginners.
Use Math.abs() to return the absolute value.
Example:
console.log(Math.abs(-5)); // Output: 5
Discover this method in the JavaScript math functions with free tutorial.
Functions like Math.sin(), Math.cos(), and Math.tan() calculate sine, cosine, and tangent, respectively, for a given angle in radians. Learn more in the JavaScript math function free course video.
Use Math.max() and Math.min().
console.log(Math.max(1, 3, 2)); // Output: 3
console.log(Math.min(1, 3, 2)); // Output: 1
Watch practical examples in the JS math function with free video tutorial.