JavaScript Math

JavaScript Tutorial

JavaScript Math

In JavaScript Math provides a built-in Math object to perform mathematical operations.
It is not a constructor — you use it directly: Math.method().


1️⃣ Basic Math Methods

🔹 Math.round()

Rounds to the nearest integer.

Math.round(4.6); // 5
Math.round(4.4); // 4

🔹 Math.ceil()

Rounds up.

Math.ceil(4.1); // 5

🔹 Math.floor()

Rounds down.

Math.floor(4.9); // 4

🔹 Math.trunc()

Removes decimal part.

Math.trunc(4.9); // 4

2️⃣ Power & Roots

🔹 Math.pow()

Math.pow(2, 3); // 8

🔹 Math.sqrt()

Math.sqrt(16); // 4

🔹 Math.cbrt()

Math.cbrt(27); // 3

3️⃣ Absolute & Sign

🔹 Math.abs()

Math.abs(-10); // 10

🔹 Math.sign()

Math.sign(-5); // -1
Math.sign(0); // 0
Math.sign(5); // 1

4️⃣ Minimum & Maximum

Math.min(10, 5, 20); // 5
Math.max(10, 5, 20); // 20

With arrays:

const nums = [3, 7, 1, 9];
Math.max(...nums); // 9

5️⃣ Random Numbers 🎲

🔹 Random between 0 and 1

Math.random();

🔹 Random between 1 and 10

Math.floor(Math.random() * 10) + 1;

🔹 Random between min and max


 


6️⃣ Trigonometric Functions

Math.sin(Math.PI / 2); // 1
Math.cos(0); // 1
Math.tan(0); // 0

📌 Angles are in radians, not degrees.


7️⃣ Logarithmic Methods

Math.log(10); // Natural log (base e)
Math.log10(100); // 2
Math.log2(8); // 3

8️⃣ Constants in Math

Math.PI; // 3.141592653589793
Math.E; // 2.718281828459045
Math.SQRT2; // √2

9️⃣ Practical Examples

✔ Find Area of Circle

let r = 7;
let area = Math.PI * Math.pow(r, 2);
console.log(area);

✔ Round Price for Billing

let price = 99.75;
console.log(Math.round(price)); // 100

✔ Generate OTP

let otp = Math.floor(1000 + Math.random() * 9000);
console.log(otp);

Common Mistakes ❌

new Math() → invalid
❌ Forgetting radians in trigonometry
❌ Using Math.round() instead of Math.floor() for random numbers


Quick Summary 📌

Method Purpose
round() Nearest integer
ceil() Round up
floor() Round down
random() Random number
pow() Power
sqrt() Square root
min()/max() Smallest / Largest

You may also like...