LearnContact
Lesson 2050 min read

JavaScript Math

Learn how to perform mathematical calculations in JavaScript using the Math object, including rounding, powers, roots, random numbers, trigonometry, logarithms, and practical calculations.

Introduction

Mathematical calculations are an essential part of programming. Applications use mathematics for prices, discounts, taxes, measurements, games, animations, statistics, charts, scientific calculations, random values, and many other features.

JavaScript provides the built-in Math object for performing common mathematical operations. It contains useful constants such as PI and methods for rounding numbers, calculating powers and roots, finding minimum and maximum values, generating random numbers, and performing advanced mathematical calculations.

Unlike many JavaScript objects, the Math object is not created using the new keyword. Its properties and methods are accessed directly using Math followed by a dot.

What You Will Learn
  • What the JavaScript Math object is.
  • Why applications need mathematical calculations.
  • How the Math object works.
  • Why Math is not used with the new keyword.
  • How to use mathematical constants.
  • How to use Math.PI.
  • How to use Math.E.
  • How to round numbers.
  • How Math.round() works.
  • How Math.floor() works.
  • How Math.ceil() works.
  • How Math.trunc() works.
  • How rounding methods differ.
  • How Math.sign() works.
  • How to calculate absolute values.
  • How to calculate powers.
  • How to calculate square roots.
  • How to calculate cube roots.
  • How to calculate distances using Math.hypot().
  • How to find minimum values.
  • How to find maximum values.
  • How to use Math.min() and Math.max() with arrays.
  • How to generate random numbers.
  • How to generate random integers.
  • How to generate random numbers within a range.
  • How to select random array items.
  • How to generate random booleans.
  • How to generate random colors.
  • How to generate random passwords.
  • How to simulate dice rolls.
  • How to simulate coin tosses.
  • How to generate OTP values.
  • How trigonometric methods work.
  • Why JavaScript trigonometric methods use radians.
  • How to convert degrees and radians.
  • How logarithmic methods work.
  • How exponential methods work.
  • Why floating-point precision problems occur.
  • How to round numbers to decimal places.
  • How to calculate percentages.
  • How to calculate discounts.
  • How to calculate taxes.
  • How to calculate averages.
  • How to calculate distances.
  • How to clamp numbers within a range.
  • How to map numbers from one range to another.
  • How to build a complete interactive calculator.

What is the Math Object?

The Math object is a built-in JavaScript object that provides mathematical constants and functions.

Basic Math Example
console.log(
    Math.PI
);

console.log(
    Math.sqrt(25)
);

console.log(
    Math.max(
        10,
        50,
        20
    )
);
Output

Math.PI is a property, while Math.sqrt() and Math.max() are methods.

Math Object Structure
JAVASCRIPT MATH OBJECT

┌──────────────────────────────┐
│           Math               │
├──────────────────────────────┤
│ Properties                   │
│                              │
│ Math.PI                      │
│ Math.E                       │
│ Math.SQRT2                   │
│ Math.LN2                     │
├──────────────────────────────┤
│ Methods                      │
│                              │
│ Math.round()                 │
│ Math.floor()                 │
│ Math.ceil()                  │
│ Math.abs()                   │
│ Math.pow()                   │
│ Math.sqrt()                  │
│ Math.min()                   │
│ Math.max()                   │
│ Math.random()                │
└──────────────────────────────┘

Why Do We Need Math?

Applications frequently need to calculate values, compare quantities, generate random results, transform measurements, and process numeric information.

E-Commerce

Calculate prices, discounts, taxes, shipping costs, and totals.

Games

Generate random values, calculate movement, distance, angles, and scores.

Data Analysis

Calculate averages, ranges, percentages, and statistics.

Animations

Calculate positions, movement, rotation, scaling, and timing.

Geometry

Calculate areas, distances, angles, circles, and dimensions.

Finance

Calculate interest, profit, loss, tax, and investment values.

Security

Generate temporary random values and verification codes.

Scientific Apps

Perform powers, roots, logarithms, and trigonometric calculations.

User Interfaces

Clamp values, calculate progress, and map ranges.

Simulations

Generate random events such as dice rolls and coin tosses.

Real-World Analogy

Think of the Math object like a scientific calculator that is always available inside JavaScript.

Scientific Calculator Analogy
┌─────────────────────────────┐
│    SCIENTIFIC CALCULATOR    │
├─────────────────────────────┤
│                             │
│  π       √       x²         │
│                             │
│  sin     cos     tan        │
│                             │
│  log     min     max        │
│                             │
│  round   floor   ceil       │
│                             │
└──────────────┬──────────────┘
               │
               ▼

        JavaScript Math

Math.PI
Math.sqrt()
Math.pow()
Math.sin()
Math.log()
Math.min()
Math.max()
Math.round()

How the Math Object Works

The Math object is a static built-in object. This means its properties and methods are accessed directly through Math.

Correct Math Usage
const result =
    Math.sqrt(64);

console.log(result);
Output
Do Not Create Math Object
// ❌ Incorrect
// const math = new Math();


// ✅ Correct
const result =
    Math.round(4.7);

console.log(result);
Do Not Use new Math()
  • Math is not a constructor.
  • Do not use the new keyword.
  • Access properties directly with Math.property.
  • Call methods directly with Math.method().

Math Object Syntax

Math Syntax
PROPERTY

Math.property


METHOD

Math.method(value)


MULTIPLE VALUES

Math.method(
    value1,
    value2,
    value3
)


Examples:

Math.PI

Math.round(4.7)

Math.sqrt(25)

Math.max(
    10,
    20,
    30
)

Math.random()

Math Properties

The Math object provides several predefined mathematical constants.

Math Constants
console.log(Math.PI);
console.log(Math.E);
console.log(Math.SQRT2);
console.log(Math.SQRT1_2);
console.log(Math.LN2);
console.log(Math.LN10);
console.log(Math.LOG2E);
console.log(Math.LOG10E);

Math.PI

Math.PI returns the mathematical constant π, approximately 3.14159. It is commonly used in calculations involving circles.

PI Value
console.log(
    Math.PI
);
Output
Circle Circumference
const radius = 5;

const circumference =
    2
    * Math.PI
    * radius;

console.log(
    circumference
);
Output
Circle Area
const radius = 5;

const area =
    Math.PI
    * radius ** 2;

console.log(area);
Output

Math.E

Math.E returns Euler’s number, approximately 2.718. It is commonly used in exponential growth, logarithms, finance, and scientific calculations.

Euler Number
console.log(
    Math.E
);
Output

Other Math Constants

Math Constants Summary
Property          Meaning
----------------------------------------
Math.PI           π

Math.E            Euler's Number

Math.SQRT2        Square Root of 2

Math.SQRT1_2      Square Root of 1/2

Math.LN2          Natural Logarithm of 2

Math.LN10         Natural Logarithm of 10

Math.LOG2E        Base-2 Logarithm of E

Math.LOG10E       Base-10 Logarithm of E

Rounding Numbers

JavaScript provides several Math methods for converting decimal numbers into integer values. Each method follows a different rounding rule.

Math.round()

Math.round() rounds a number to the nearest integer.

Round Numbers
console.log(
    Math.round(4.4)
);

console.log(
    Math.round(4.5)
);

console.log(
    Math.round(4.8)
);
Output

Math.floor()

Math.floor() rounds a number downward toward negative infinity.

Floor Numbers
console.log(
    Math.floor(4.9)
);

console.log(
    Math.floor(4.1)
);

console.log(
    Math.floor(-4.1)
);
Output

Math.ceil()

Math.ceil() rounds a number upward toward positive infinity.

Ceiling Numbers
console.log(
    Math.ceil(4.1)
);

console.log(
    Math.ceil(4.9)
);

console.log(
    Math.ceil(-4.9)
);
Output

Math.trunc()

Math.trunc() removes the decimal portion of a number without rounding.

Truncate Numbers
console.log(
    Math.trunc(4.9)
);

console.log(
    Math.trunc(4.1)
);

console.log(
    Math.trunc(-4.9)
);
Output

Rounding Comparison

Rounding Methods Comparison
Value: 4.7

Math.round(4.7)   → 5
Math.floor(4.7)   → 4
Math.ceil(4.7)    → 5
Math.trunc(4.7)   → 4


Value: -4.7

Math.round(-4.7)  → -5
Math.floor(-4.7)  → -5
Math.ceil(-4.7)   → -4
Math.trunc(-4.7)  → -4

Math.sign()

Math.sign() identifies whether a number is positive, negative, zero, or negative zero.

Number Sign
console.log(
    Math.sign(25)
);

console.log(
    Math.sign(-25)
);

console.log(
    Math.sign(0)
);
Output

Absolute Values

The absolute value of a number represents its distance from zero without considering direction. Therefore, the absolute value is never negative.

Math.abs()

Absolute Values
console.log(
    Math.abs(10)
);

console.log(
    Math.abs(-10)
);

console.log(
    Math.abs(-25.5)
);
Output
Difference Between Numbers
const first = 20;
const second = 35;

const difference =
    Math.abs(
        first - second
    );

console.log(difference);
Output

Powers

A power represents repeated multiplication. For example, 2 raised to the power of 3 equals 2 × 2 × 2.

Math.pow()

Calculate Powers
console.log(
    Math.pow(2, 3)
);

console.log(
    Math.pow(5, 2)
);

console.log(
    Math.pow(10, 3)
);
Output

Exponentiation Operator

Modern JavaScript provides the exponentiation operator ** as an alternative to Math.pow().

Exponentiation Operator
console.log(
    2 ** 3
);

console.log(
    5 ** 2
);
Output

Square Roots

The square root of a number is a value that produces the original number when multiplied by itself.

Math.sqrt()

Square Roots
console.log(
    Math.sqrt(25)
);

console.log(
    Math.sqrt(64)
);

console.log(
    Math.sqrt(2)
);
Output
Negative Square Root
console.log(
    Math.sqrt(-25)
);
Output

Cube Roots

Math.cbrt()

Math.cbrt() returns the cube root of a number.

Cube Roots
console.log(
    Math.cbrt(8)
);

console.log(
    Math.cbrt(27)
);

console.log(
    Math.cbrt(-8)
);
Output

Math.hypot()

Math.hypot() returns the square root of the sum of the squares of its arguments. It is useful for calculating distances.

Hypotenuse
const result =
    Math.hypot(
        3,
        4
    );

console.log(result);
Output

Minimum Values

Math.min()

Math.min() returns the smallest value from the provided arguments.

Find Minimum
const minimum =
    Math.min(
        50,
        10,
        80,
        5,
        30
    );

console.log(minimum);
Output

Maximum Values

Math.max()

Math.max() returns the largest value from the provided arguments.

Find Maximum
const maximum =
    Math.max(
        50,
        10,
        80,
        5,
        30
    );

console.log(maximum);
Output

Min and Max with Arrays

Math.min() and Math.max() expect individual arguments. The spread operator can pass array elements as separate values.

Array Minimum and Maximum
const scores = [
    72,
    91,
    65,
    88,
    99
];

const minimum =
    Math.min(
        ...scores
    );

const maximum =
    Math.max(
        ...scores
    );

console.log(minimum);
console.log(maximum);
Output

Random Numbers

Random numbers are useful in games, simulations, quizzes, random selections, colors, verification codes, and many other applications.

Math.random()

Math.random() returns a pseudo-random decimal number greater than or equal to 0 and less than 1.

Random Decimal
const random =
    Math.random();

console.log(random);
Example Output
Math.random() Range
  • The minimum possible value is 0.
  • The maximum is less than 1.
  • The value changes between executions.
  • The returned number is a decimal.
  • Math.random() is not designed for cryptographic security.

Random Decimal Range

Random Decimal from 0 to 10
const random =
    Math.random() * 10;

console.log(random);
Random Decimal Between Min and Max
function randomDecimal(
    min,
    max
) {
    return (
        Math.random()
        * (max - min)
        + min
    );
}

console.log(
    randomDecimal(
        10,
        20
    )
);

Random Integer

Random Integer from 0 to 9
const random =
    Math.floor(
        Math.random() * 10
    );

console.log(random);
Random Integer Flow
Math.random()

Example:
0.6384

    │
    ▼

× 10

6.384

    │
    ▼

Math.floor()

6

Random Integer Range

A reusable function can generate a random integer between an inclusive minimum and maximum value.

Random Integer Function
function randomInteger(
    min,
    max
) {
    return (
        Math.floor(
            Math.random()
            * (
                max
                - min
                + 1
            )
        )
        + min
    );
}

console.log(
    randomInteger(
        1,
        10
    )
);
Random Range Formula
Inclusive Random Integer

Math.floor(
    Math.random()
    * (
        max
        - min
        + 1
    )
)
+ min


Example:

min = 1
max = 6

Possible Results:

1, 2, 3, 4, 5, 6

Random Array Item

Select Random Item
const colors = [
    'Red',
    'Blue',
    'Green',
    'Yellow',
    'Purple'
];

const randomIndex =
    Math.floor(
        Math.random()
        * colors.length
    );

const randomColor =
    colors[randomIndex];

console.log(randomColor);

Random Boolean

Random True or False
const randomBoolean =
    Math.random() < 0.5;

console.log(
    randomBoolean
);

Random Color

Random RGB Color
function randomColor() {
    const red =
        Math.floor(
            Math.random() * 256
        );

    const green =
        Math.floor(
            Math.random() * 256
        );

    const blue =
        Math.floor(
            Math.random() * 256
        );

    return (
        `rgb(${red}, ${green}, ${blue})`
    );
}

console.log(
    randomColor()
);
Example Output

Random Password

Simple Random Password
function generatePassword(
    length
) {
    const characters =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        + 'abcdefghijklmnopqrstuvwxyz'
        + '0123456789'
        + '!@#$%';

    let password = '';


    for (
        let i = 0;
        i < length;
        i++
    ) {
        const randomIndex =
            Math.floor(
                Math.random()
                * characters.length
            );

        password +=
            characters[randomIndex];
    }


    return password;
}

console.log(
    generatePassword(12)
);
Security Warning
  • Math.random() is useful for learning and ordinary random interface behavior.
  • Math.random() is not cryptographically secure.
  • Do not use Math.random() for real passwords, authentication tokens, reset tokens, or security-sensitive secrets.
  • Security-sensitive randomness should use a cryptographically secure API.

Dice Simulation

Roll a Dice
function rollDice() {
    return (
        Math.floor(
            Math.random() * 6
        )
        + 1
    );
}

console.log(
    rollDice()
);
Possible Output

Coin Toss

Heads or Tails
function tossCoin() {
    return (
        Math.random() < 0.5
        ? 'Heads'
        : 'Tails'
    );
}

console.log(
    tossCoin()
);

OTP Generator

Six-Digit Demo OTP
function generateOTP() {
    return (
        Math.floor(
            100000
            +
            Math.random()
            * 900000
        )
    );
}

console.log(
    generateOTP()
);
Example Output
Demo Use Only
  • This example demonstrates random number ranges.
  • Math.random() should not be used for security-sensitive authentication codes.
  • Real authentication systems require cryptographically secure randomness.

Trigonometric Methods

The Math object provides trigonometric methods for working with angles. These methods are useful in graphics, games, animations, geometry, physics, and engineering.

Radians and Degrees

JavaScript trigonometric methods use radians instead of degrees.

Degrees and Radians
Degrees        Radians
----------------------------
0°             0

90°            π / 2

180°           π

270°           3π / 2

360°           2π


Conversion:

Degrees → Radians

degrees × π / 180


Radians → Degrees

radians × 180 / π

Math.sin()

Math.sin() returns the sine of an angle measured in radians.

Sine
const angle =
    90
    * Math.PI
    / 180;

console.log(
    Math.sin(angle)
);
Output

Math.cos()

Cosine
const angle =
    0
    * Math.PI
    / 180;

console.log(
    Math.cos(angle)
);
Output

Math.tan()

Tangent
const angle =
    45
    * Math.PI
    / 180;

console.log(
    Math.tan(angle)
);
Example Output

The result may not display as exactly 1 because JavaScript numbers use floating-point representation.

Inverse Trigonometry

Inverse Trigonometric Methods
console.log(
    Math.asin(1)
);

console.log(
    Math.acos(1)
);

console.log(
    Math.atan(1)
);

Math.asin(), Math.acos(), and Math.atan() return angles in radians.

Math.atan2()

Math.atan2() returns the angle between the positive x-axis and a point represented by y and x coordinates.

Calculate Direction Angle
const x = 10;
const y = 10;

const radians =
    Math.atan2(
        y,
        x
    );

const degrees =
    radians
    * 180
    / Math.PI;

console.log(degrees);
Output

Logarithmic Methods

Logarithms are used in scientific calculations, algorithms, data analysis, growth calculations, and computer science.

Math.log()

Math.log() returns the natural logarithm of a number using base e.

Natural Logarithm
console.log(
    Math.log(Math.E)
);
Output

Math.log10()

Base-10 Logarithm
console.log(
    Math.log10(100)
);

console.log(
    Math.log10(1000)
);
Output

Math.log2()

Base-2 Logarithm
console.log(
    Math.log2(8)
);

console.log(
    Math.log2(1024)
);
Output

Exponential Methods

Math.exp()

Math.exp() returns Euler’s number e raised to the specified power.

Exponential Value
console.log(
    Math.exp(1)
);

console.log(
    Math.E
);
Output

Math.expm1()

Math.expm1(x) returns e raised to x minus 1. It can provide better precision for values close to zero.

Exponential Minus One
console.log(
    Math.expm1(1)
);

Math.log1p()

Math.log1p(x) returns the natural logarithm of 1 + x and can provide better precision for values close to zero.

Logarithm of One Plus Value
console.log(
    Math.log1p(1)
);

Floating-Point Precision

JavaScript stores numbers using binary floating-point representation. Some decimal fractions cannot be represented exactly, which can produce unexpected results.

Precision Problem
const result =
    0.1 + 0.2;

console.log(result);
Output
Why Precision Problems Happen
Decimal Number

0.1

    │
    ▼

Converted to Binary

Cannot be represented exactly

    │
    ▼

Stored as an approximation

    │
    ▼

Calculation

0.1 + 0.2

    │
    ▼

0.30000000000000004

Fixing Decimal Precision

Integer Scaling
const result =
    (
        0.1 * 10
        +
        0.2 * 10
    )
    / 10;

console.log(result);
Output

toFixed() with Math

toFixed() formats a number with a fixed number of decimal places. It returns a string.

Fixed Decimal Places
const price =
    99.4567;

const formatted =
    price.toFixed(2);

console.log(formatted);

console.log(
    typeof formatted
);
Output
Convert Back to Number
const value =
    Number(
        (
            0.1 + 0.2
        ).toFixed(2)
    );

console.log(value);

console.log(
    typeof value
);
Output

Rounding to Decimal Places

Round to Two Decimal Places
function roundTo(
    value,
    decimalPlaces
) {
    const factor =
        10 ** decimalPlaces;

    return (
        Math.round(
            value * factor
        )
        / factor
    );
}

console.log(
    roundTo(
        12.3456,
        2
    )
);

console.log(
    roundTo(
        12.3456,
        3
    )
);
Output

Percentage Calculations

Calculate Percentage
const obtainedMarks = 425;
const totalMarks = 500;

const percentage =
    (
        obtainedMarks
        / totalMarks
    )
    * 100;

console.log(
    percentage
);
Output

Discount Calculations

Calculate Discount
const price = 2000;
const discountPercent = 15;

const discount =
    price
    * discountPercent
    / 100;

const finalPrice =
    price - discount;

console.log(
    discount
);

console.log(
    finalPrice
);
Output

Tax Calculations

Calculate Tax
const price = 1000;
const taxRate = 18;

const tax =
    price
    * taxRate
    / 100;

const total =
    price + tax;

console.log(tax);
console.log(total);
Output

Average Calculation

Calculate Average
const scores = [
    80,
    90,
    70,
    100
];

const total =
    scores.reduce(
        (
            sum,
            score
        ) =>
            sum + score,
        0
    );

const average =
    total
    / scores.length;

console.log(average);
Output

Distance Calculation

The distance between two points can be calculated using the differences between their coordinates.

Distance Between Two Points
function distance(
    x1,
    y1,
    x2,
    y2
) {
    const deltaX =
        x2 - x1;

    const deltaY =
        y2 - y1;

    return Math.hypot(
        deltaX,
        deltaY
    );
}

console.log(
    distance(
        0,
        0,
        3,
        4
    )
);
Output

Clamp a Number

Clamping limits a number so that it cannot go below a minimum value or above a maximum value.

Clamp Function
function clamp(
    value,
    min,
    max
) {
    return Math.min(
        Math.max(
            value,
            min
        ),
        max
    );
}

console.log(
    clamp(
        150,
        0,
        100
    )
);

console.log(
    clamp(
        -20,
        0,
        100
    )
);

console.log(
    clamp(
        75,
        0,
        100
    )
);
Output

Map a Number Range

Mapping converts a number from one range into the equivalent position in another range.

Map Range Function
function mapRange(
    value,
    inputMin,
    inputMax,
    outputMin,
    outputMax
) {
    return (
        (
            value - inputMin
        )
        *
        (
            outputMax - outputMin
        )
        /
        (
            inputMax - inputMin
        )
        +
        outputMin
    );
}

const result =
    mapRange(
        50,
        0,
        100,
        0,
        1
    );

console.log(result);
Output

Degrees to Radians

Convert Degrees to Radians
function toRadians(
    degrees
) {
    return (
        degrees
        * Math.PI
        / 180
    );
}

console.log(
    toRadians(180)
);
Output

Radians to Degrees

Convert Radians to Degrees
function toDegrees(
    radians
) {
    return (
        radians
        * 180
        / Math.PI
    );
}

console.log(
    toDegrees(Math.PI)
);
Output

Complete Math Example

The following example creates an interactive Math Toolkit. The user can enter numbers and perform calculations including rounding, powers, square roots, minimum and maximum values, percentages, and random number generation.

index.html
<div class="math-toolkit">
    <h2>Math Toolkit</h2>

    <div class="input-group">
        <label for="firstNumber">
            First Number
        </label>

        <input
            id="firstNumber"
            type="number"
            placeholder="Enter first number"
        >
    </div>

    <div class="input-group">
        <label for="secondNumber">
            Second Number
        </label>

        <input
            id="secondNumber"
            type="number"
            placeholder="Enter second number"
        >
    </div>

    <div class="button-grid">
        <button data-action="round">
            Round First
        </button>

        <button data-action="floor">
            Floor First
        </button>

        <button data-action="ceil">
            Ceil First
        </button>

        <button data-action="power">
            First ^ Second
        </button>

        <button data-action="sqrt">
            Square Root
        </button>

        <button data-action="minimum">
            Minimum
        </button>

        <button data-action="maximum">
            Maximum
        </button>

        <button data-action="percentage">
            Percentage
        </button>

        <button data-action="random">
            Random Range
        </button>
    </div>

    <div class="result-box">
        <p>Result</p>

        <strong id="result">
            0
        </strong>

        <span id="message">
            Choose an operation.
        </span>
    </div>
</div>
script.js
const firstNumberInput =
    document.getElementById(
        'firstNumber'
    );

const secondNumberInput =
    document.getElementById(
        'secondNumber'
    );

const resultElement =
    document.getElementById(
        'result'
    );

const messageElement =
    document.getElementById(
        'message'
    );

const buttons =
    document.querySelectorAll(
        '[data-action]'
    );


buttons.forEach(
    function (button) {
        button.addEventListener(
            'click',
            function () {
                calculate(
                    button.dataset.action
                );
            }
        );
    }
);


function calculate(action) {
    const first =
        Number(
            firstNumberInput.value
        );

    const second =
        Number(
            secondNumberInput.value
        );


    if (
        firstNumberInput.value === ''
    ) {
        showResult(
            '—',
            'Enter the first number.'
        );

        return;
    }


    let result;
    let message;


    switch (action) {
        case 'round':
            result =
                Math.round(first);

            message =
                `Rounded ${first}`;

            break;


        case 'floor':
            result =
                Math.floor(first);

            message =
                `Floor value of ${first}`;

            break;


        case 'ceil':
            result =
                Math.ceil(first);

            message =
                `Ceiling value of ${first}`;

            break;


        case 'sqrt':
            if (first < 0) {
                showResult(
                    'NaN',
                    'Square root requires a non-negative number.'
                );

                return;
            }

            result =
                Math.sqrt(first);

            message =
                `Square root of ${first}`;

            break;


        case 'power':
            if (
                secondNumberInput.value
                ===
                ''
            ) {
                showResult(
                    '—',
                    'Enter the second number.'
                );

                return;
            }

            result =
                Math.pow(
                    first,
                    second
                );

            message =
                `${first} raised to ${second}`;

            break;


        case 'minimum':
            if (
                secondNumberInput.value
                ===
                ''
            ) {
                showResult(
                    '—',
                    'Enter the second number.'
                );

                return;
            }

            result =
                Math.min(
                    first,
                    second
                );

            message =
                'Smaller value';

            break;


        case 'maximum':
            if (
                secondNumberInput.value
                ===
                ''
            ) {
                showResult(
                    '—',
                    'Enter the second number.'
                );

                return;
            }

            result =
                Math.max(
                    first,
                    second
                );

            message =
                'Larger value';

            break;


        case 'percentage':
            if (
                secondNumberInput.value
                ===
                ''
            ) {
                showResult(
                    '—',
                    'Enter the second number.'
                );

                return;
            }

            if (second === 0) {
                showResult(
                    '—',
                    'The total cannot be zero.'
                );

                return;
            }

            result =
                (
                    first
                    / second
                )
                * 100;

            message =
                `${first} is this percentage of ${second}`;

            break;


        case 'random':
            if (
                secondNumberInput.value
                ===
                ''
            ) {
                showResult(
                    '—',
                    'Enter the second number.'
                );

                return;
            }

            const min =
                Math.min(
                    first,
                    second
                );

            const max =
                Math.max(
                    first,
                    second
                );

            result =
                Math.floor(
                    Math.random()
                    * (
                        max
                        - min
                        + 1
                    )
                )
                + min;

            message =
                `Random integer from ${min} to ${max}`;

            break;


        default:
            showResult(
                '—',
                'Unknown operation.'
            );

            return;
    }


    showResult(
        formatResult(result),
        message
    );
}


function formatResult(value) {
    if (
        Number.isInteger(value)
    ) {
        return value;
    }


    return Number(
        value.toFixed(6)
    );
}


function showResult(
    result,
    message
) {
    resultElement.textContent =
        result;

    messageElement.textContent =
        message;
}
Browser Output
What This Example Demonstrates
  • Reading numeric values from HTML inputs.
  • Converting strings into numbers.
  • Validating empty input values.
  • Using Math.round().
  • Using Math.floor().
  • Using Math.ceil().
  • Using Math.sqrt().
  • Using Math.pow().
  • Using Math.min().
  • Using Math.max().
  • Using Math.random().
  • Generating random integers within a range.
  • Calculating percentages.
  • Preventing division by zero.
  • Validating square root input.
  • Using switch statements.
  • Using data attributes.
  • Using event listeners.
  • Using reusable functions.
  • Formatting decimal results.
  • Updating the DOM.
  • Building an interactive mathematical application.

Math Processing Flow

Math Processing Flow
NUMERIC INPUT
      │
      ▼
┌─────────────────────────────┐
│ CONVERT                     │
│                             │
│ Number()                    │
│ parseInt()                  │
│ parseFloat()                │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│ VALIDATE                    │
│                             │
│ Number.isNaN()              │
│ Number.isFinite()           │
│ Range Checks                │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│ CALCULATE                   │
│                             │
│ Arithmetic Operators        │
│ Math Methods                │
│ Custom Formula              │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│ CONTROL PRECISION           │
│                             │
│ Math.round()                │
│ toFixed()                   │
│ Scaling                     │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│ FORMAT                      │
│                             │
│ Number                      │
│ Percentage                  │
│ Currency                    │
│ Measurement                 │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│ OUTPUT                      │
│                             │
│ User Interface              │
│ API                         │
│ Chart                       │
│ Report                      │
└─────────────────────────────┘

Real-World Applications

Shopping Carts

Calculate totals, discounts, taxes, shipping, and final prices.

Games

Generate random events, calculate movement, scores, angles, and distances.

Dashboards

Calculate percentages, averages, minimums, maximums, and trends.

Financial Apps

Calculate interest, profit, loss, installments, and investment growth.

Geometry Tools

Calculate areas, distances, angles, and dimensions.

Graphics

Calculate coordinates, rotations, scaling, and animations.

Simulations

Generate random outcomes and probability-based events.

Progress Controls

Clamp progress values and map values between ranges.

Converters

Convert temperatures, distances, weights, and other measurements.

Calculators

Build basic, scientific, financial, and specialized calculators.

Statistics

Process averages, ranges, distributions, and numerical datasets.

Mapping

Calculate positions, directions, distances, and coordinates.

Common Beginner Mistakes

Avoid These Mistakes
  • Trying to create the Math object with new Math().
  • Forgetting that Math methods are static.
  • Writing math.round() instead of Math.round().
  • Forgetting that JavaScript is case-sensitive.
  • Using Math.PI() as if PI were a function.
  • Forgetting that Math.PI is a property.
  • Confusing Math.round() with Math.floor().
  • Confusing Math.floor() with Math.trunc().
  • Assuming Math.floor() simply removes decimals from negative numbers.
  • Assuming Math.ceil() always increases the absolute value.
  • Ignoring negative-number behavior in rounding methods.
  • Expecting Math.sqrt() of a negative number to return a real number.
  • Forgetting that Math.sqrt(-1) returns NaN.
  • Using Math.pow() with arguments in the wrong order.
  • Confusing the base with the exponent.
  • Forgetting that ** is the exponentiation operator.
  • Using ^ for exponentiation.
  • Forgetting that ^ is a bitwise XOR operator in JavaScript.
  • Passing an array directly to Math.min().
  • Passing an array directly to Math.max().
  • Forgetting to use the spread operator with arrays.
  • Calling Math.min() with no arguments and expecting zero.
  • Calling Math.max() with no arguments and expecting zero.
  • Assuming Math.random() can return exactly 1.
  • Forgetting that Math.random() returns a decimal.
  • Using Math.round() for random integer ranges without understanding uneven probability.
  • Forgetting +1 in an inclusive random integer formula.
  • Adding the minimum value in the wrong place.
  • Generating an array index using array.length as an inclusive maximum.
  • Allowing a random array index equal to array.length.
  • Using Math.random() for real passwords.
  • Using Math.random() for authentication tokens.
  • Using Math.random() for security-sensitive OTP values.
  • Assuming pseudo-random means cryptographically secure.
  • Forgetting that trigonometric methods use radians.
  • Passing degrees directly to Math.sin().
  • Passing degrees directly to Math.cos().
  • Passing degrees directly to Math.tan().
  • Forgetting to convert inverse trigonometric results from radians when degrees are needed.
  • Reversing x and y arguments in Math.atan2().
  • Expecting every floating-point calculation to be exact.
  • Comparing decimal calculations directly without considering precision.
  • Expecting 0.1 + 0.2 to equal exactly 0.3.
  • Using toFixed() and forgetting that it returns a string.
  • Performing arithmetic directly on a toFixed() result without considering conversion.
  • Rounding too early during multi-step calculations.
  • Formatting values before calculations are complete.
  • Using floating-point numbers carelessly for financial calculations.
  • Assuming Number input values are automatically numbers.
  • Forgetting that HTML input values are strings.
  • Using + with input strings and accidentally concatenating them.
  • Failing to validate NaN.
  • Failing to check for Infinity.
  • Dividing by zero without validation.
  • Calculating percentages with the formula reversed.
  • Applying a discount percentage incorrectly.
  • Adding tax when tax should already be included.
  • Dividing an average by the wrong number of values.
  • Calculating an average of an empty array.
  • Forgetting to handle minimum and maximum range order.
  • Creating a random range function that fails when min is greater than max.
  • Using Math.abs() when the direction of a difference is important.
  • Using Math.floor() when standard rounding is required.
  • Using Math.ceil() when truncation is required.
  • Using Math.trunc() when downward rounding is required.
  • Forgetting that Math.sign(NaN) returns NaN.
  • Assuming all Math methods return integers.
  • Displaying excessively long decimal values to users.
  • Rounding display values without preserving the original calculation value.
  • Hardcoding PI as 3.14 when Math.PI provides greater precision.
  • Writing repeated random-number formulas instead of reusable functions.
  • Writing repeated conversion formulas instead of reusable functions.
  • Failing to document whether ranges are inclusive or exclusive.
Common Math Mistakes
// ❌ Math is not a constructor
// const math = new Math();


// ❌ PI is not a function
// Math.PI();


// ✅ PI is a property
console.log(
    Math.PI
);


// ❌ ^ is not exponentiation
console.log(
    2 ^ 3
);
// 1


// ✅ Use **
console.log(
    2 ** 3
);
// 8


const numbers = [
    10,
    20,
    30
];


// ❌ Array passed directly
console.log(
    Math.max(numbers)
);
// NaN


// ✅ Spread array values
console.log(
    Math.max(...numbers)
);
// 30


// ❌ Degrees passed directly
console.log(
    Math.sin(90)
);


// ✅ Convert to radians
console.log(
    Math.sin(
        90
        * Math.PI
        / 180
    )
);
// 1


// Floating-point precision
console.log(
    0.1 + 0.2
);
// 0.30000000000000004

Best Practices

  • Access Math properties and methods directly through Math.
  • Do not use new Math().
  • Remember that JavaScript is case-sensitive.
  • Use Math.PI instead of manually writing an approximate PI value.
  • Use Math.round() for nearest-integer rounding.
  • Use Math.floor() for downward rounding.
  • Use Math.ceil() for upward rounding.
  • Use Math.trunc() when only the decimal portion should be removed.
  • Test rounding behavior with negative numbers.
  • Use Math.abs() when only the magnitude of a difference matters.
  • Use ** for clear exponentiation in modern JavaScript.
  • Use Math.sqrt() for square roots.
  • Use Math.cbrt() for cube roots.
  • Use Math.hypot() for distance calculations.
  • Use Math.min() and Math.max() for individual numeric arguments.
  • Use the spread operator when passing arrays to Math.min() and Math.max().
  • Validate arrays before calculating minimum and maximum values.
  • Use Math.random() for ordinary non-security-sensitive randomness.
  • Do not use Math.random() for authentication or cryptographic secrets.
  • Clearly define whether random ranges are inclusive or exclusive.
  • Use Math.floor() for evenly distributed random integer ranges.
  • Use reusable functions for random range generation.
  • Ensure random array indexes are always less than array.length.
  • Remember that trigonometric methods use radians.
  • Create reusable degree-to-radian conversion functions.
  • Create reusable radian-to-degree conversion functions.
  • Use Math.atan2() for direction calculations involving coordinates.
  • Expect floating-point precision limitations.
  • Avoid direct equality comparisons for calculated decimal values when precision matters.
  • Use an appropriate tolerance when comparing floating-point results.
  • Remember that toFixed() returns a string.
  • Convert formatted strings back to numbers only when further calculation is required.
  • Delay rounding until the appropriate stage of a calculation.
  • Keep raw calculation values separate from display values.
  • Use integer scaling carefully for decimal calculations.
  • Use specialized decimal or financial strategies when exact monetary arithmetic is required.
  • Convert HTML input values into numbers before calculations.
  • Validate numeric input before performing calculations.
  • Check for NaN when input may be invalid.
  • Check for finite values when Infinity is not acceptable.
  • Prevent division by zero where required.
  • Use descriptive variable names such as percentage, radius, total, minimum, and maximum.
  • Store repeated formulas in reusable functions.
  • Keep calculation logic separate from DOM manipulation when possible.
  • Test minimum values.
  • Test maximum values.
  • Test zero.
  • Test negative numbers.
  • Test decimal values.
  • Test very large values.
  • Test invalid input.
  • Test boundary conditions.
  • Document units such as degrees, radians, pixels, meters, and percentages.
  • Document whether ranges include their minimum and maximum values.
  • Format final output for users without unnecessarily changing internal values.

Frequently Asked Questions

What is the Math object in JavaScript?

The Math object is a built-in object that provides mathematical constants and methods.

Do I need to create a Math object?

No. Math properties and methods are accessed directly through Math.

Can I use new Math()?

No. Math is not a constructor.

What is Math.PI?

Math.PI is the mathematical constant π, approximately 3.141592653589793.

Is Math.PI a method?

No. It is a property.

What is Math.E?

Math.E is Euler’s number, approximately 2.718281828459045.

What does Math.round() do?

It rounds a number to the nearest integer.

What does Math.floor() do?

It rounds a number downward toward negative infinity.

What does Math.ceil() do?

It rounds a number upward toward positive infinity.

What does Math.trunc() do?

It removes the decimal portion without rounding.

What is the difference between Math.floor() and Math.trunc()?

Math.floor() rounds toward negative infinity, while Math.trunc() simply removes the decimal portion.

What does Math.sign() return?

It indicates whether a number is positive, negative, zero, or negative zero.

What does Math.abs() do?

It returns the absolute non-negative value of a number.

How do I calculate a power?

Use Math.pow(base, exponent) or the ** operator.

Does ^ calculate powers in JavaScript?

No. The ^ operator performs bitwise XOR.

How do I calculate a square root?

Use Math.sqrt().

What does Math.sqrt() return for a negative number?

NaN.

How do I calculate a cube root?

Use Math.cbrt().

What does Math.hypot() do?

It calculates the square root of the sum of squared arguments and is useful for distances.

How do I find the smallest number?

Use Math.min().

How do I find the largest number?

Use Math.max().

How do I use Math.min() with an array?

Use the spread operator, such as Math.min(...numbers).

How do I use Math.max() with an array?

Use the spread operator, such as Math.max(...numbers).

What does Math.random() return?

A pseudo-random decimal number greater than or equal to 0 and less than 1.

Can Math.random() return 1?

No. The result is always less than 1.

Can Math.random() return 0?

Yes.

How do I generate a random integer?

Multiply Math.random() by a range and use Math.floor().

How do I generate a random integer from 1 to 6?

Use Math.floor(Math.random() * 6) + 1.

How do I generate a random integer between min and max?

Use Math.floor(Math.random() * (max - min + 1)) + min for an inclusive range.

How do I select a random array item?

Generate a random index from 0 to array.length - 1.

Can Math.random() be used for passwords?

It should not be used for security-sensitive passwords or secrets because it is not cryptographically secure.

Can Math.random() be used for real OTP authentication?

Not for security-sensitive authentication. Use cryptographically secure randomness.

How do I simulate a dice roll?

Generate a random integer from 1 to 6.

How do I simulate a coin toss?

Compare Math.random() with 0.5 and return one of two results.

Do JavaScript trigonometric methods use degrees?

No. They use radians.

How do I convert degrees to radians?

Multiply degrees by Math.PI and divide by 180.

How do I convert radians to degrees?

Multiply radians by 180 and divide by Math.PI.

What does Math.sin() return?

The sine of an angle in radians.

What does Math.cos() return?

The cosine of an angle in radians.

What does Math.tan() return?

The tangent of an angle in radians.

What do Math.asin(), Math.acos(), and Math.atan() return?

They return angles in radians.

What does Math.atan2() do?

It calculates an angle from y and x coordinates.

What does Math.log() calculate?

The natural logarithm of a number.

What does Math.log10() calculate?

The base-10 logarithm of a number.

What does Math.log2() calculate?

The base-2 logarithm of a number.

What does Math.exp() do?

It returns Euler’s number e raised to a specified power.

Why is 0.1 + 0.2 not exactly 0.3?

Because some decimal fractions cannot be represented exactly using binary floating-point numbers.

How do I format a number to two decimal places?

Use toFixed(2), remembering that it returns a string.

Does toFixed() return a number?

No. It returns a string.

How do I round to a specific number of decimal places?

Multiply by a power of 10, round, and divide by the same power of 10.

How do I calculate a percentage?

Divide the obtained value by the total value and multiply by 100.

How do I calculate a discount?

Multiply the price by the discount percentage divided by 100, then subtract the discount from the price.

How do I calculate tax?

Multiply the base price by the tax percentage divided by 100.

How do I calculate an average?

Add all values and divide the total by the number of values.

How do I calculate the distance between two points?

Calculate coordinate differences and use Math.hypot().

What does clamping mean?

Clamping restricts a value so it remains between a minimum and maximum.

How do I clamp a number?

A common formula is Math.min(Math.max(value, min), max).

What does mapping a range mean?

It converts a value from its relative position in one range to the equivalent position in another range.

Are JavaScript Math calculations always exact?

No. Floating-point representation can produce small precision differences.

Should I round during every calculation step?

Usually no. Keep useful precision during calculations and round at the appropriate final stage.

Are HTML number input values automatically numbers?

No. Input values are strings and should be converted before mathematical calculations.

Key Takeaways

  • The Math object provides mathematical constants and methods.
  • Math is a static built-in object.
  • Math should not be created using the new keyword.
  • Math.PI represents π.
  • Math.E represents Euler’s number.
  • Math.round() rounds to the nearest integer.
  • Math.floor() rounds downward.
  • Math.ceil() rounds upward.
  • Math.trunc() removes the decimal portion.
  • Math.sign() identifies the sign of a number.
  • Math.abs() returns an absolute value.
  • Math.pow() calculates powers.
  • The ** operator also calculates powers.
  • The ^ operator does not calculate powers.
  • Math.sqrt() calculates square roots.
  • Math.cbrt() calculates cube roots.
  • Math.hypot() is useful for distance calculations.
  • Math.min() finds the smallest value.
  • Math.max() finds the largest value.
  • The spread operator can pass array values to Math.min() and Math.max().
  • Math.random() generates a pseudo-random decimal from 0 up to but not including 1.
  • Math.floor() is commonly used to generate random integers.
  • Inclusive random ranges require careful range calculations.
  • Random array items are selected using random indexes.
  • Math.random() is not suitable for cryptographic security.
  • Trigonometric methods use radians.
  • Degrees can be converted to radians.
  • Radians can be converted to degrees.
  • Math.sin() calculates sine.
  • Math.cos() calculates cosine.
  • Math.tan() calculates tangent.
  • Math.atan2() calculates direction angles.
  • Math.log() calculates natural logarithms.
  • Math.log10() calculates base-10 logarithms.
  • Math.log2() calculates base-2 logarithms.
  • Math.exp() performs exponential calculations.
  • Floating-point calculations may have precision limitations.
  • toFixed() formats decimal places but returns a string.
  • Numbers can be rounded to custom decimal places.
  • Math is useful for percentages, discounts, taxes, and averages.
  • Math.hypot() can calculate distances between points.
  • Clamping keeps values within boundaries.
  • Range mapping converts values between different scales.
  • Mathematical input should be converted and validated before calculation.

Summary

The JavaScript Math object provides constants and methods for performing common and advanced mathematical calculations.

Unlike constructor-based objects, Math is used directly without the new keyword. Its properties and methods are accessed through the Math object.

Math.PI and Math.E provide important mathematical constants, while rounding methods such as Math.round(), Math.floor(), Math.ceil(), and Math.trunc() provide different ways to process decimal values.

Math.abs(), Math.pow(), Math.sqrt(), Math.cbrt(), and Math.hypot() support calculations involving magnitudes, powers, roots, and distances.

Math.min() and Math.max() identify minimum and maximum values. Arrays can be used with these methods through the spread operator.

Math.random() generates pseudo-random decimal values. Combined with Math.floor(), it can generate random integers, dice rolls, coin tosses, random array selections, and other non-security-sensitive random behavior.

Trigonometric methods such as Math.sin(), Math.cos(), and Math.tan() work with radians. Degree values must be converted before being used with these methods.

JavaScript also provides logarithmic and exponential methods for scientific and advanced calculations.

Floating-point calculations can produce small precision differences. Applications should understand when and how to round values without unnecessarily losing precision.

Mastering the Math object allows you to build calculators, games, shopping carts, dashboards, financial tools, animations, geometry applications, random generators, simulations, and many other numeric features.

Lesson 20 Completed
  • You understand the JavaScript Math object.
  • You understand how the Math object works.
  • You know why Math does not use the new keyword.
  • You can use Math constants.
  • You can use Math.PI.
  • You can use Math.E.
  • You can round numbers.
  • You can use Math.round().
  • You can use Math.floor().
  • You can use Math.ceil().
  • You can use Math.trunc().
  • You understand rounding differences.
  • You can use Math.sign().
  • You can calculate absolute values.
  • You can calculate powers.
  • You can use the exponentiation operator.
  • You can calculate square roots.
  • You can calculate cube roots.
  • You can calculate distances with Math.hypot().
  • You can find minimum values.
  • You can find maximum values.
  • You can use Math.min() and Math.max() with arrays.
  • You can generate random decimal values.
  • You can generate random integers.
  • You can generate random values within ranges.
  • You can select random array items.
  • You can generate random booleans.
  • You can generate random colors.
  • You understand the security limitations of Math.random().
  • You can simulate dice rolls.
  • You can simulate coin tosses.
  • You understand trigonometric methods.
  • You can convert degrees and radians.
  • You can use logarithmic methods.
  • You can use exponential methods.
  • You understand floating-point precision.
  • You can round to decimal places.
  • You can calculate percentages.
  • You can calculate discounts.
  • You can calculate taxes.
  • You can calculate averages.
  • You can calculate distances.
  • You can clamp numbers.
  • You can map values between ranges.
  • You can build a complete interactive Math Toolkit.
  • You are ready to learn the JavaScript DOM.
Next Lesson →

JavaScript DOM