DEV Community

King coder
King coder

Posted on

JavaScript Math Object Methods – Beginner Guide

1. Math.ceil()

What it does:

Rounds a number up to the next whole number.

When to use:

When you always want to round up, even if the decimal is small.

Where to use:

Calculating minimum payments, ticket prices, or rounding up quantities.

Example:

Math.ceil(4.1); // 5
Math.ceil(7.9); // 8
Math.ceil(2);   // 2
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Expecting it to round normally (it always rounds UP).

2. Math.floor()

What it does:

Rounds a number down to the previous whole number.

When to use:

When you always want to round down.

Where to use:

Calculating discounts, splitting bills, or limiting values.

Example:

Math.floor(4.9); // 4
Math.floor(7.1); // 7
Math.floor(2);   // 2
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Expecting it to round normally (it always rounds DOWN).

3. Math.round()

What it does:

Rounds a number to the nearest whole number.

When to use:

When you want standard rounding (0.5 and above rounds up).

Where to use:

Rounding prices, scores, or measurements.

Example:

Math.round(4.4); // 4
Math.round(4.5); // 5
Math.round(4.6); // 5
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Not realizing 0.5 rounds UP.

4. Math.trunc()

What it does:

Removes the decimal part, returns only the integer part.

When to use:

When you want to ignore decimals without rounding.

Where to use:

Extracting whole numbers from calculations.

Example:

Math.trunc(4.9); // 4
Math.trunc(-4.9); // -4
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Thinking it rounds (it just chops off decimals).

5. Math.random()

What it does:

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

When to use:

Whenever you need randomness.

Where to use:

Games, random selections, shuffling, generating random IDs.

Example:

Math.random(); // e.g., 0.345678
// Random integer between 1 and 10:
Math.floor(Math.random() * 10) + 1;
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Forgetting to scale and round for integer ranges.

6. Math.max()

What it does:

Returns the largest value from a list of numbers.

When to use:

Finding the maximum value.

Where to use:

Finding highest score, price, or measurement.

Example:

Math.max(4, 7, 1); // 7
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Passing an array directly (use spread operator):
const arr = [4, 7, 1];
Math.max(...arr); // 7
Enter fullscreen mode Exit fullscreen mode

7. Math.min()

What it does:

Returns the smallest value from a list of numbers.

When to use:

Finding the minimum value.

Where to use:

Finding lowest score, price, or measurement.

Example:

Math.min(4, 7, 1); // 1
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Passing an array directly (use spread operator):
const arr = [4, 7, 1];
Math.min(...arr); // 1
Enter fullscreen mode Exit fullscreen mode

8. Math.pow()

What it does:

Raises a number to the power of another number.

When to use:

Calculating exponents.

Where to use:

Interest calculations, geometry, physics formulas.

Example:

Math.pow(2, 3); // 8 (2^3)
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Using ^ for exponentiation (use Math.pow() or **).

9. Math.sqrt()

What it does:

Returns the square root of a number.

When to use:

Calculating roots.

Where to use:

Geometry, statistics, physics.

Example:

Math.sqrt(9); // 3
Math.sqrt(2); // 1.414...
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Passing negative numbers (returns NaN).

10. Math.abs()

What it does:

Returns the absolute (positive) value of a number.

When to use:

Removing negative signs.

Where to use:

Distance calculations, score differences.

Example:

Math.abs(-5); // 5
Math.abs(5);  // 5
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Not realizing it works for both positive and negative numbers.

11. Math.PI

What it does:

Represents the value of π (pi), about 3.14159.

When to use:

Circle calculations.

Where to use:

Geometry, trigonometry.

Example:

console.log(Math.PI); // 3.141592653589793
// Area of a circle with radius r:
let r = 5;
let area = Math.PI * Math.pow(r, 2);
console.log(area); // 78.53981633974483
Enter fullscreen mode Exit fullscreen mode

Common mistakes:

  • Typing PI instead of Math.PI.

Real-World Examples

Rounding prices in a shopping cart

let price = 4.567;
let roundedPrice = Math.round(price * 100) / 100; // 4.57
Enter fullscreen mode Exit fullscreen mode

Generating random numbers for games

// Random dice roll (1-6)
let dice = Math.floor(Math.random() * 6) + 1;
Enter fullscreen mode Exit fullscreen mode

Finding min/max values in an array

let scores = [10, 5, 8, 12];
let maxScore = Math.max(...scores); // 12
let minScore = Math.min(...scores); // 5
Enter fullscreen mode Exit fullscreen mode

Calculating square roots for geometry

let area = 25;
let side = Math.sqrt(area); // 5
Enter fullscreen mode Exit fullscreen mode

Creating math-based conditions in code

let temp = -7;
if (Math.abs(temp) > 5) {
  console.log("Temperature is extreme!");
}
Enter fullscreen mode Exit fullscreen mode

21. Generate a 4-Digit OTP

Task:

Write a function that generates a random 4-digit OTP (One-Time Password).

Formula:

OTP = Math.floor(Math.random() * 9000) + 1000

Example:

generateOTP() // 4821 (could be any number from 1000 to 9999)


22. Calculate Area of a Rectangle

Given:

Length = l, Width = w

Formula:

Area = length × width

Example:

If l = 8, w = 5

Area = 8 × 5 = 40


23. Calculate Area of a Circle

Given:

Radius = r

Formula:

Area = π × r²

Example:

If r = 7

Area = Math.PI * Math.pow(7, 2) ≈ 153.94


24. Calculate Simple Interest

Given:

Principal = P, Rate = R, Time = T

Formula:

Simple Interest = (P × R × T) / 100

Example:

If P = 1000, R = 5, T = 2

Simple Interest = (1000 × 5 × 2) / 100 = 100


25. Calculate Perimeter of a Square

Given:

Side = s

Formula:

Perimeter = 4 × side

Example:

If s = 6

Perimeter = 4 × 6 = 24


26. Calculate Average of Numbers

Given:

Numbers: [10, 20, 30, 40]

Formula:

Average = (Sum of numbers) / (Total numbers)

Example:

Average = (10 + 20 + 30 + 40) / 4 = 25


Tip:

For all math problems, write the formula first, then plug in the values!

Tip:

Always check the documentation for edge cases and remember that most Math methods work with numbers, not arrays (use the spread operator for arrays).

Top comments (0)