- Home
- /
- JS Math
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS Math
JavaScript Math Object
In JavaScript, the Math
object is like your built-in calculator. You don’t need to create it — it’s ready to use with a collection of methods and constants to perform mathematical tasks like rounding, generating random numbers, or finding max/min values.
Let’s explore some of the most useful features of the Math
object.
Generating Random Numbers
The Math.random()
method generates a floating-point number between 0 (inclusive) and 1 (exclusive). This is helpful when you want to simulate randomness — for example, in games or quizzes.
let randomValue = Math.random();
console.log(randomValue); // e.g. 0.7642891432
Want a random number between 1 and 10?
let randomInt = Math.floor(Math.random() * 10) + 1;
console.log(randomInt); // Any integer between 1 and 10
Rounding Numbers
Use these methods when you need to control how decimal numbers behave:
console.log(Math.floor(7.9)); // Rounds down → 7
console.log(Math.ceil(2.1)); // Rounds up → 3
console.log(Math.round(4.5)); // Nearest int → 5
console.log(Math.round(4.4)); // Nearest int → 4
Each one serves a specific purpose depending on whether you want to round up, down, or to the nearest integer.
Finding Maximum and Minimum Values
These methods come in handy when comparing multiple values:
let highest = Math.max(10, 20, 30, 5);
let lowest = Math.min(10, 20, 30, 5);
console.log("Max:", highest); // Max: 30
console.log("Min:", lowest); // Min: 5
You can also use them with arrays by spreading the values:
let marks = [45, 88, 92, 60];
console.log(Math.max(...marks)); // 92
Square Roots and Exponents
JavaScript’s Math
object also helps with more complex operations:
console.log(Math.sqrt(64)); // 8 (square root)
console.log(Math.pow(3, 4)); // 81 (3 raised to power 4)
Absolute Values
To ensure a number is positive regardless of its sign:
console.log(Math.abs(-25)); // 25
Useful Constants
console.log(Math.PI); // 3.141592653589793 (π)
console.log(Math.E); // 2.718281828459045 (Euler's Number)
You can use these constants in formulas — e.g., to calculate the area of a circle:
let radius = 7;
let area = Math.PI * Math.pow(radius, 2);
console.log("Circle Area:", area.toFixed(2)); // e.g. 153.94
Conclusion
The Math
object in JavaScript gives you a wide range of tools:
Generate random numbers
Round values up/down
Find max or min in data
Use mathematical constants like π
Work with square roots and powers
Whether you’re building quizzes, animations, or calculators, mastering Math
brings you closer to writing smarter and more interactive code.