JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Math Object

8 April 2025 | Category:

The JavaScript Math object lets you perform mathematical operations. It provides a collection of properties and methods that can be used to work with numbers, perform calculations, and get useful mathematical values.

The Math object is not a constructor, so you don’t need to create it. Just use it directly like: Math.method() or Math.property.


✅ Common Math Methods

MethodDescription
Math.round(x)Rounds x to the nearest integer
Math.ceil(x)Rounds x up to the next integer
Math.floor(x)Rounds x down to the previous int
Math.trunc(x)Removes the decimal part (ES6)
Math.sign(x)Returns -1, 0, or 1 based on sign
Math.abs(x)Absolute value (removes negative sign)
Math.pow(x, y)x raised to the power of y
Math.sqrt(x)Square root of x
Math.min(...nums)Lowest value from a list of numbers
Math.max(...nums)Highest value from a list of numbers
Math.random()Returns a random number (0 to <1)

🔍 Examples

console.log(Math.round(4.6));    // 5
console.log(Math.ceil(4.1));     // 5
console.log(Math.floor(4.9));    // 4
console.log(Math.trunc(4.9));    // 4
console.log(Math.sign(-50));     // -1
console.log(Math.abs(-10));      // 10
console.log(Math.pow(2, 3));     // 8
console.log(Math.sqrt(16));      // 4
console.log(Math.min(10, 5, 30)); // 5
console.log(Math.max(10, 5, 30)); // 30
console.log(Math.random());      // 0.0 - 0.999...

🎲 Generating Random Numbers

Random number between 0 and 10:

const num = Math.floor(Math.random() * 11);
console.log(num); // 0 to 10

Random number between 1 and 100:

const num = Math.floor(Math.random() * 100) + 1;
console.log(num); // 1 to 100

🔢 Math Constants

PropertyDescription
Math.PI3.141592653…
Math.EEuler’s number (≈2.718)
Math.LN2Natural log of 2
Math.LN10Natural log of 10
Math.LOG2ELog base 2 of E
Math.LOG10ELog base 10 of E
Math.SQRT2Square root of 2
Math.SQRT1_2Square root of 1/2

Example:

console.log(Math.PI); // 3.141592653589793

📌 Summary

  • Math is a static object, used without creating an instance.
  • It provides methods for rounding, power, square root, etc.
  • Useful for game development, calculations, animations, and more.