JS Tutorial



JS MATH


JavaScript Math ๐Ÿ“

The Math object in JavaScript provides mathematical constants and functions. Itโ€™s not a constructor, so you donโ€™t use new Math(). Just call its methods directly like Math.random() or Math.floor().

๐Ÿ”ข Math Constants

  • Math.PI โ†’ 3.14159...
  • Math.E โ†’ Eulerโ€™s number (2.718...)
  • Math.SQRT2 โ†’ โˆš2
console.log(Math.PI);      // 3.141592653589793
console.log(Math.E);       // 2.718281828459045
  

๐Ÿ“ Rounding Methods

  • Math.round(x) โ€“ Nearest integer
  • Math.floor(x) โ€“ Down to nearest integer
  • Math.ceil(x) โ€“ Up to nearest integer
  • Math.trunc(x) โ€“ Remove decimal part
Math.round(4.7);   // 5
Math.floor(4.7);   // 4
Math.ceil(4.3);    // 5
Math.trunc(4.9);   // 4
  

๐Ÿ” Useful Math Methods

  • Math.max(...) โ€“ Highest value
  • Math.min(...) โ€“ Lowest value
  • Math.pow(x, y) โ€“ x to the power y
  • Math.sqrt(x) โ€“ Square root
  • Math.abs(x) โ€“ Absolute (positive) value
Math.max(5, 10, 15);     // 15
Math.min(-2, 0, 4);      // -2
Math.pow(2, 3);          // 8
Math.sqrt(16);           // 4
Math.abs(-7);            // 7
  

๐ŸŽฒ Random Number Generator

Math.random() returns a random number between 0 (inclusive) and 1 (exclusive).

Math.random();          // e.g., 0.7263521

// Random number between 1 and 100:
Math.floor(Math.random() * 100) + 1;
  

๐ŸŽฎ Live Example: Random Number Generator

Click the button

๐Ÿ” Bonus: Dice Roller ๐ŸŽฒ

// Simulate a 6-sided die roll
let roll = Math.floor(Math.random() * 6) + 1;
console.log("You rolled:", roll);
  
Tip: You can combine Math.random() with Math.floor() to create custom ranges.

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review