JavaScript Math Object and Date/Time
JavaScript provides two powerful built-in objects for working with numbers and dates: the Math object and the Date object. These built-in tools save developers from writing complex mathematical logic or date handling code from scratch.
The Math Object
The Math object is a built-in JavaScript object that contains mathematical constants and functions. It does not need to be created — it is always available.
Math Constants
| Constant | Value | Description |
|---|---|---|
| Math.PI | 3.14159... | The value of π (Pi) |
| Math.E | 2.71828... | Euler's number |
| Math.SQRT2 | 1.41421... | Square root of 2 |
| Math.LN2 | 0.69314... | Natural log of 2 |
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045
console.log(Math.SQRT2); // 1.4142135623730951Rounding Methods
Math.round() — Round to Nearest Integer
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.round(-3.6)); // -4Math.floor() — Round Down (Towards Negative Infinity)
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(4.1)); // 4
console.log(Math.floor(-3.1)); // -4Math.ceil() — Round Up (Towards Positive Infinity)
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(4.9)); // 5
console.log(Math.ceil(-3.9)); // -3Math.trunc() — Remove Decimal, No Rounding
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4Math.abs() — Absolute Value (Remove Negative Sign)
console.log(Math.abs(-15)); // 15
console.log(Math.abs(15)); // 15Math.max() and Math.min() — Find Largest and Smallest
console.log(Math.max(10, 50, 30, 90, 20)); // 90
console.log(Math.min(10, 50, 30, 90, 20)); // 10
// With an array, use spread operator
let scores = [75, 88, 62, 91, 70];
console.log(Math.max(...scores)); // 91
console.log(Math.min(...scores)); // 62Math.pow() — Power (Exponentiation)
console.log(Math.pow(2, 10)); // 1024
console.log(Math.pow(5, 3)); // 125Math.sqrt() — Square Root
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(144)); // 12Math.random() — Random Number Between 0 and 1
Math.random() returns a decimal number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random()); // e.g., 0.7342891...
// Random whole number between 1 and 10
let random = Math.floor(Math.random() * 10) + 1;
console.log(random); // e.g., 7
// Random number between min and max (inclusive)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(5, 15)); // e.g., 11Math.log() — Logarithm
console.log(Math.log(Math.E)); // 1 (natural log)
console.log(Math.log2(8)); // 3 (log base 2)
console.log(Math.log10(1000)); // 3 (log base 10)The Date Object
The Date object in JavaScript provides methods to work with dates and times. It can read the current date and time, create specific dates, compare dates, and format them.
Creating a Date Object
// Current date and time
let now = new Date();
console.log(now);
// e.g., Sun Mar 08 2026 14:30:00 GMT+0530
// Specific date
let birthday = new Date("1995-06-15");
console.log(birthday);
// Date with time
let meeting = new Date("2026-03-10T09:30:00");
console.log(meeting);Getting Date Components
let today = new Date();
console.log(today.getFullYear()); // e.g., 2026
console.log(today.getMonth()); // 0-11 (0 = January)
console.log(today.getDate()); // 1-31 (day of month)
console.log(today.getDay()); // 0-6 (0 = Sunday)
console.log(today.getHours()); // 0-23
console.log(today.getMinutes()); // 0-59
console.log(today.getSeconds()); // 0-59
console.log(today.getTime()); // Milliseconds since Jan 1, 1970Important: getMonth() returns 0 for January, 1 for February, and so on. Always add 1 for display purposes.
let today = new Date();
let displayMonth = today.getMonth() + 1;
console.log("Current month:", displayMonth); // e.g., 3 (for March)Setting Date Components
let date = new Date();
date.setFullYear(2027);
date.setMonth(11); // December (0-indexed)
date.setDate(25); // 25th day
console.log(date); // Dec 25, 2027Formatting Dates for Display
let today = new Date();
// Using toLocaleDateString()
console.log(today.toLocaleDateString());
// e.g., "3/8/2026" (varies by locale)
// Formatted with options
let options = { year: "numeric", month: "long", day: "numeric" };
console.log(today.toLocaleDateString("en-IN", options));
// e.g., "8 March 2026"
// ISO Format
console.log(today.toISOString());
// e.g., "2026-03-08T09:00:00.000Z"Calculating Time Difference
Dates can be subtracted in JavaScript. The result is in milliseconds.
let startDate = new Date("2025-01-01");
let endDate = new Date("2026-01-01");
let diffMs = endDate - startDate; // Milliseconds
let diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); // Convert to days
console.log(diffDays + " days between dates."); // 365 days between dates.Countdown Timer Example
let today = new Date();
let newYear = new Date("2027-01-01");
let msLeft = newYear - today;
let daysLeft = Math.floor(msLeft / (1000 * 60 * 60 * 24));
console.log(`Days until New Year 2027: ${daysLeft}`);Practical Example — Age Calculator
function calculateAge(birthDateStr) {
let birthDate = new Date(birthDateStr);
let today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
let monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--; // Birthday hasn't happened yet this year
}
return age;
}
console.log(calculateAge("1995-06-15")); // e.g., 30Key Points to Remember
- The
Mathobject provides mathematical constants and functions — no need to create it Math.round()rounds to nearest,Math.floor()rounds down,Math.ceil()rounds upMath.random()returns a decimal between 0 and 1 — use withMath.floor()to get integersMath.max()andMath.min()work with the spread operator...on arrays- Use
new Date()to get the current date and time getMonth()returns 0–11 (January = 0) — always add 1 for display- Subtracting two Date objects gives the difference in milliseconds
- Use
toLocaleDateString()to format dates for display
