JS Math
In this page:
Math.round(number);
Math.random();
Math.max(a, b);
Math.floor(number);
Math.PI
Rounding: round, floor, and ceil
Math.round() rounds to the nearest whole number, Math.floor() always rounds down, and Math.ceil() always rounds up, regardless of how close the decimal is to the next whole number.
उदाहरण: Rounding: round, floor, and ceil
// Print `Math.round(4.5)` to the console
// Print `Math.round(4.5)` to the console
console.log(Math.round(4.5));
// Print `Math.floor(4.9)` to the console
// Print `Math.floor(4.9)` to the console
console.log(Math.floor(4.9));
// Print `Math.ceil(4.1)` to the console
// Print `Math.ceil(4.1)` to the console
console.log(Math.ceil(4.1));
abs, max, and min
Math.abs() returns a number's absolute value, always positive, Math.max() returns the largest of a set of values, and Math.min() returns the smallest.
All three accept any number of arguments and are commonly combined with the spread operator to work on array contents.
उदाहरण: abs, max, and min
// Print `Math.abs(-5)` to the console
// Print `Math.abs(-5)` to the console
console.log(Math.abs(-5));
// Print `Math.max(3, 7, 2)` to the console
// Print `Math.max(3, 7, 2)` to the console
console.log(Math.max(3, 7, 2));
// Print `Math.min(3, 7, 2)` to the console
// Print `Math.min(3, 7, 2)` to the console
console.log(Math.min(3, 7, 2));
Math.random()
Math.random() returns a random decimal number between 0 (inclusive) and 1 (exclusive), which is typically scaled and rounded to produce a random whole number within a specific range.
उदाहरण: Math.random()
console.log(Math.random()); // decimal between 0 and 1
const diceRoll = Math.floor(Math.random() * 6) + 1;
console.log(diceRoll);
pow and sqrt
Math.pow(base, exponent) raises a number to a power, functionally equivalent to the ** operator, and Math.sqrt() calculates a number's square root.
Math.sqrt() of a negative number returns NaN, since JavaScript's Math object only works with real numbers.
उदाहरण: pow and sqrt
console.log(Math.pow(2, 3));
console.log(Math.sqrt(16));
console.log(Math.sqrt(-4)); // NaN
Math.PI and Other Constants
Math.PI provides the mathematical constant pi with full floating-point precision, useful for geometry calculations like circle area or circumference, without needing to type or remember its digits manually.
उदाहरण: Math.PI and Other Constants
console.log(Math.PI);
const radius = 5;
console.log(Math.PI * radius * radius); // circle area
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS Dates
- JS Math
- JS Conditionals
- JS Switch
- JS Loop For
- JS Loop While
- JS Iterables
- JS Sets
- JS Maps
- JS typeof
- JS Type Conversion
- JS Destructuring
- JS Arrow Functions
- JS Classes
- JS Modules
- JS Promises
- JS Async/Await
- JS DOM
- JS DOM Methods
- JS Events Advanced
- JS DOM Navigation
- JS DOM Collections
- JS Async Callbacks
- JS Async Parallel
- JS Date Set
- JS Set Logic