SyntaxPilot
Courses/JavaScript/Lesson 20
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 20 of 40

Date and Math

queued

These are the notes for JavaScript episode 20. Three everyday jobs, each with a trap: splitting a bill (100 / 3 prints 33.333333333333336 and 0.1 + 0.2 isn't 0.3), a lucky draw (Math.random() gives decimals, not dice faces), and a delivery date ("30/10/2026" + 7 is "30/10/20267"). You'll fix them with two built-in toolboxes: Math (rounding, max/min, random whole numbers) and Date (creating dates, months that start at 0, adding days, days between dates, Invalid Date, time zones and timing code). Every output below is real Node.js 24 output (node main.js); random and "now" outputs change every run.

Builds on: numbers and operators (episode 3), arrays (7), spread (12), JSON and ISO date strings (19).

The real-life idea: three friends, one chai bill

Three friends share a ₹100 bill. A calculator says ₹33.333333... forever, which nobody can pay. In real life you round: ₹33, ₹33, and one friend pays ₹34. Computers need the same rounding, for an extra reason: they store decimals slightly wrong.

Real life JavaScript
₹100 ÷ 3 never ends 100 / 3 → 33.333333333333336
Pay ₹33 or ₹34 Math.floor, Math.ceil, Math.round
Showing "₹33.33" on the bill share.toFixed(2) (a string)
Counting coins, not fractions count money in paise (whole numbers)
A lucky-draw pin on a stick Math.random()
A wall calendar Date

Part 1: Math

Decimals aren't exact

const bill = 100;
const share = bill / 3;
console.log("Each pays:", share);
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
Each pays: 33.333333333333336
0.30000000000000004
false

Why: every JavaScript number is a 64-bit floating-point number stored in binary (ones and zeros). Just as 1/3 can't be written exactly in decimal (0.333...), 0.1 can't be written exactly in binary, so a tiny rounding error appears. This isn't a JavaScript bug: Python, Java, C and Excel's engine all use the same standard (IEEE 754).

To compare decimals, allow a tiny difference:

console.log(Math.abs(0.1 + 0.2 - 0.3) < 1e-9);
true

Rounding: round, floor, ceil, trunc, toFixed

const share = 100 / 3;
console.log(Math.round(share), Math.floor(share), Math.ceil(share));
console.log(share.toFixed(2), typeof share.toFixed(2));
console.log(Math.round(share * 100) / 100);
console.log(Math.round(2.5), Math.round(-2.5));
console.log(Math.trunc(-4.7), Math.floor(-4.7));
33 33 34
33.33 string
33.33
3 -2
-4 -5
Method What it does 33.33 -4.7 2.5 / -2.5
Math.round(x) nearest whole number; halves go up (towards +∞) 33 -5 3 / -2
Math.floor(x) always down 33 -5 2 / -3
Math.ceil(x) always up 34 -4 3 / -2
Math.trunc(x) chop off the decimals (towards 0) 33 -4 2 / -2
x.toFixed(n) text with n decimals "33.33" "-4.70" "2.50"
  • toFixed returns a string: use it only for display. (33.333).toFixed(2) + 1 is "33.331".
  • Round to 2 decimals as a number: Math.round(x * 100) / 100.
  • Money rule: store and add money in paise (whole numbers: 3350 paise), and divide by 100 only to display. Whole numbers are exact.

Math.max, Math.min and friends

const marks = [72, 95, 88, 61];
console.log(Math.max(marks));
console.log(Math.max(...marks), Math.min(...marks));
console.log(Math.max());
console.log(Math.abs(-15), Math.sqrt(144), 2 ** 10, Math.PI.toFixed(4));
NaN
95 61
-Infinity
15 12 1024 3.1416
  • Math.max takes separate numbers, not an array: Math.max(marks) is NaN. Spread the array (episode 12).
  • Math.max() with nothing is -Infinity (and Math.min() is Infinity): check for an empty array first.
Method Meaning Example
Math.abs(x) distance from 0 (drop the minus) Math.abs(-15) → 15
Math.sqrt(x), Math.cbrt(x) square / cube root Math.sqrt(144) → 12, Math.cbrt(27) → 3
x ** y, Math.pow(x, y) power 2 ** 10 → 1024
Math.sign(x) -1, 0 or 1 Math.sign(-3) → -1
Math.hypot(a, b) √(a² + b²) Math.hypot(3, 4) → 5
Math.log10(x) log base 10 Math.log10(1000) → 3
Math.PI π 3.141592653589793

Math is not a class: you never write new Math(). It's one built-in object holding number tools.

Random numbers

Math.random() returns a decimal from 0 up to, but not including, 1. To get a whole number in a range, stretch, floor, shift:

Math.random()                    0 ≤ x < 1        (a pin on a 1 m stick)
Math.random() * 6                0 ≤ x < 6        (stretch the stick to 6 m)
Math.floor(Math.random() * 6)    0, 1, 2, 3, 4, 5 (read the whole metre mark)
Math.floor(Math.random() * 6) + 1   1 to 6        (shift: a dice)
console.log(Math.random());
console.log(Math.random());
console.log(Math.random() * 6);
0.6816221096657573
0.8912377394710247
4.283896913475575

(Different every run.)

function rollDice() {
  return Math.floor(Math.random() * 6) + 1;
}
console.log(rollDice(), rollDice(), rollDice(), rollDice());
const players = ["Asha", "Ravi", "Meena", "Kabir"];
const i = Math.floor(Math.random() * players.length);
console.log("Winner:", players[i]);
const otp = Math.floor(100000 + Math.random() * 900000);
console.log("OTP:", otp);
1 6 5 4
Winner: Kabir
OTP: 389311

(Your numbers will differ.) The general formula, a whole number from min to max inclusive:

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Security: Math.random() is fine for games and shuffles, but it is predictable. Real OTPs, tokens and passwords must use the crypto module: require("node:crypto").randomInt(100000, 1000000).

Part 2: Date

The problem: a date in text

const ordered = "30/10/2026";
console.log("Delivery:", ordered + 7);
Delivery: 30/10/20267

A date in a string is just characters; + glued a 7 on. And even with numbers, 28 October + 7 is "35 October": months have 28 to 31 days and there are leap years. We need something that knows the calendar.

Creating dates

const now = new Date();
console.log(now);
console.log(typeof now, now.getFullYear());
const d = new Date(2026, 11, 5);   // 5 November?
console.log(d.toDateString());
console.log(d.getMonth(), d.getDate(), d.getDay());
2026-10-30T20:45:07.414Z
object 2026
Sat Dec 05 2026
11 5 6

Months count from 0. January is 0, November is 10, December is 11, so new Date(2026, 11, 5) is 5 December. Days of the month start at 1. getDay() is the weekday with Sunday = 0 (Saturday = 6).

Ways to make a Date Example Note
now new Date() the current moment
parts (local time) new Date(2026, 9, 30, 15, 0) month from 0
ISO string new Date("2026-10-30"), new Date("2026-10-30T09:30:00Z") the safe text format
milliseconds new Date(0) → 1970-01-01T00:00:00.000Z ms since 1 Jan 1970 UTC
copy new Date(other) a separate Date
Getter Gives Setter
getFullYear() 2026 setFullYear(y)
getMonth() 0-11 setMonth(m)
getDate() 1-31 setDate(d)
getDay() 0-6, Sunday = 0 (none)
getHours(), getMinutes(), getSeconds() time parts setHours(...) etc.
getTime() ms since 1970 UTC setTime(ms)

Each getter has a getUTC... twin that reads the UTC clock instead of the local one.

Date maths: adding days and days between

const ordered = new Date(2026, 9, 28);   // 28 Oct
const delivery = new Date(ordered);
delivery.setDate(delivery.getDate() + 7);
console.log(ordered.toDateString());
console.log(delivery.toDateString());
const exam = new Date(2026, 11, 15);    // 15 Dec
const ms = exam - ordered;
console.log("Days to exam:", Math.round(ms / (1000 * 60 * 60 * 24)));
console.log(new Date(2026, 1, 30).toDateString());
Wed Oct 28 2026
Wed Nov 04 2026
Days to exam: 48
Mon Mar 02 2026
  • setDate(getDate() + 7) asked for "day 35 of October"; Date rolls over into November. This works across months and years.
  • Copy first (new Date(ordered)): setters change the Date object.
  • Subtracting two Dates gives milliseconds. One day = 1000 × 60 × 60 × 24 = 86,400,000 ms. Use Math.round, because in countries with daylight saving one "day" can be 23 or 25 hours.
  • "30 February" silently became 2 March: Date never complains about impossible days. To validate a date from a form, build it and check the parts came back unchanged (practice 3).

Invalid Date and the safe format

const a = new Date("31/10/2026");
console.log(a, a.getTime());
const b = new Date("2026-10-31");
console.log(b.toDateString());
Invalid Date NaN
Sat Oct 31 2026

JavaScript doesn't read Indian day/month/year text. No error is thrown: you get an Invalid Date whose getTime() is NaN, so check with isNaN(date). The format every engine reads is ISO 8601: YYYY-MM-DD, optionally with a time YYYY-MM-DDTHH:mm:ssZ. (A date-only ISO string means midnight UTC.)

Time zones

The same moment is 09:30 in London (UTC in winter), 15:00 in India (IST, UTC+5:30) and 05:30 in New York (EDT). A Date stores one moment, as milliseconds since 1 January 1970 UTC (the Unix epoch). How you show it is a separate choice:

const t = new Date("2026-10-30T09:30:00Z");
console.log(t.toISOString());
console.log(t.toLocaleString("en-IN", { timeZone: "Asia/Kolkata" }));
console.log(t.toLocaleDateString("en-IN", {
  timeZone: "Asia/Kolkata", weekday: "long",
  day: "numeric", month: "long", year: "numeric" }));
const start = Date.now();
let sum = 0;
for (let i = 0; i < 1e7; i++) sum += i;
console.log("Took", Date.now() - start, "ms");
2026-10-30T09:30:00.000Z
30/10/2026, 3:00:00 pm
Friday, 30 October 2026
Took 14 ms
  • toISOString() always shows UTC; the Z means "zero offset". This is what JSON stores (episode 19).
  • toLocaleString(locale, { timeZone }) formats for a language and a time zone: "en-IN" gives day/month order, "Asia/Kolkata" is IST.
  • Date.now() is the current time in ms: the difference of two calls times your code. (Your number will differ.)
  • Rule: store and send times in UTC (ISO strings or ms); convert to local time only to show them.

Common mistakes (and what really happens)

You wrote What happens Why Fix
0.1 + 0.2 === 0.3 false (0.30000000000000004) binary can't store most decimals exactly compare with a tolerance; money in paise
(33.333).toFixed(2) + 1 "33.331" toFixed returns a string display only; Math.round(x * 100) / 100 for numbers
Math.round(-2.5) -2 halves round towards +∞ know it; or round the absolute value
Math.floor(-4.7) expecting -4 -5 floor always goes down Math.trunc(-4.7)
Math.max(marks) NaN max wants separate numbers Math.max(...marks)
Math.max(...[]) -Infinity no numbers to compare check arr.length first
Math.random() * 6 as a dice 5.83... random gives decimals Math.floor(Math.random() * 6) + 1
Math.random() for an OTP predictable not cryptographically secure crypto.randomInt
"30/10/2026" + 7 "30/10/20267" text, not a date new Date(...) and setDate
new Date(2026, 11, 5) for 5 Nov Sat Dec 05 2026 months count from 0 new Date(2026, 10, 5)
new Date("31/10/2026") Invalid Date, getTime() → NaN not a format JS reads "2026-10-31"
new Date(2026, 1, 30) Mon Mar 02 2026, no error overflow rolls over validate the parts
(b - a) / 86400000 across DST 48.041666... a day can be 23/25 h Math.round(...)

Mini project: split any bill fairly

Split a bill among any number of friends, in paise, so the shares add up exactly; then print a due date 7 days later.

function splitBill(totalRupees, names) {
  const paise = Math.round(totalRupees * 100);
  const base = Math.floor(paise / names.length);
  let extra = paise - base * names.length;
  return names.map((name) => {
    const share = base + (extra > 0 ? 1 : 0);
    if (extra > 0) extra--;
    return `${name.padEnd(6)} ₹${(share / 100).toFixed(2)}`;
  });
}
console.log(splitBill(100, ["Asha", "Ravi", "Meena"]).join("\n"));
console.log(splitBill(250.75, ["Asha", "Ravi", "Meena", "Kabir"]).join("\n"));

const ordered = new Date(2026, 9, 28);
const due = new Date(ordered);
due.setDate(due.getDate() + 7);
console.log("Due:", due.toLocaleDateString("en-IN", { weekday: "short", day: "numeric", month: "short", year: "numeric" }));
Asha   ₹33.34
Ravi   ₹33.33
Meena  ₹33.33
Asha   ₹62.69
Ravi   ₹62.69
Meena  ₹62.69
Kabir  ₹62.68
Due: Wed, 4 Nov, 2026

The leftover paise go one each to the first friends, so 3334 + 3333 + 3333 = 10000 paise exactly: nothing lost to rounding.

Practice

  1. Shuffle the quiz questions ["Q1", "Q2", "Q3", "Q4", "Q5"] into a random order (every order equally likely).
  2. Print someone's age in days, born 15 August 2005, on 30 October 2026.
  3. Write isValidDate(y, m, d) with a normal month number (1-12). Test 30 Feb 2026, 29 Feb 2028 and 31 Oct 2026.
  4. Write randInt(min, max) and check ten calls of randInt(5, 8) are all between 5 and 8.
Solutions
  1. The Fisher-Yates shuffle: walk backwards, swap each item with a random earlier one (or itself).
function shuffle(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}
console.log(shuffle(["Q1", "Q2", "Q3", "Q4", "Q5"]));
[ 'Q4', 'Q2', 'Q3', 'Q1', 'Q5' ]      (random)

(arr.sort(() => Math.random() - 0.5) looks shorter but is not fair.)

2.

const birth = new Date(2005, 7, 15);
const today = new Date(2026, 9, 30);
const days = Math.round((today - birth) / (1000 * 60 * 60 * 24));
console.log("Age in days:", days);
Age in days: 7746

3.

function isValidDate(y, m, d) {
  const date = new Date(y, m - 1, d);
  return date.getFullYear() === y && date.getMonth() === m - 1 && date.getDate() === d;
}
console.log(isValidDate(2026, 2, 30), isValidDate(2028, 2, 29), isValidDate(2026, 10, 31));
false true true

30 Feb rolls over to March, so the month no longer matches. 2028 is a leap year.

4.

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
const rolls = Array.from({ length: 10 }, () => randInt(5, 8));
console.log(rolls.every((r) => r >= 5 && r <= 8), Math.min(...rolls) >= 5);
true true

Quick quiz

What does this print?

const d = new Date(2026, 0, 31);
d.setDate(d.getDate() + 1);
console.log(d.getMonth(), d.getDate());
  • A. 1 1
  • B. 0 32
  • C. 2 1
  • D. Invalid Date
Answer

A. 31 January + 1 day rolls over to 1 February. February is month 1 (months start at 0), and the day is 1.

Interview questions

  • Why is 0.1 + 0.2 !== 0.3 in JavaScript? How do you compare decimals safely?
  • How should an app store money amounts?
  • What's the difference between Math.round, Math.floor, Math.ceil and Math.trunc for negative numbers?
  • What does toFixed return?
  • How do you get a random whole number between min and max inclusive? Why not use it for OTPs?
  • Why is Math.max([1, 2]) NaN? What is Math.max()?
  • Why does new Date(2026, 11, 5) give December?
  • How do you add 7 days to a date? How do you count the days between two dates?
  • What is an Invalid Date and how do you detect it?
  • What is the Unix epoch? What is UTC? What does the Z in an ISO string mean?
  • How do you show a date in Indian Standard Time?

Glossary

Term Meaning Example
Floating-point number a number stored as binary digits plus an exponent; most decimals are approximate 0.1 + 0.2 → 0.30000000000000004
Binary base 2: only the digits 0 and 1 5 is 101
IEEE 754 the standard for floating-point numbers used by almost every language JavaScript's Number
Math a built-in object of number tools (not a class) Math.round(2.4)
Round / floor / ceil / trunc nearest / down / up / towards zero Math.ceil(33.3) → 34
toFixed(n) number → text with n decimals (2.5).toFixed(2) → "2.50"
Paise 1/100 of a rupee; money as whole numbers ₹33.50 = 3350 paise
NaN "not a number": the result of an invalid number operation Math.max([1, 2])
Infinity bigger than any number Math.min()
Math.random() a decimal from 0 up to (not including) 1 0.62126...
Pseudo-random looks random but is computed; can be predicted Math.random()
Cryptographically secure random numbers that can't be predicted crypto.randomInt
Date a built-in object for one moment in time new Date()
Unix epoch 1 January 1970 00:00 UTC, the zero point for Date new Date(0)
Timestamp a moment as ms since the epoch Date.now()
UTC Coordinated Universal Time, the world's reference clock the Z in ISO strings
IST Indian Standard Time, UTC+5:30 timeZone: "Asia/Kolkata"
Time zone a region's offset from UTC "America/New_York"
Daylight saving time (DST) clocks moved an hour in summer in some countries a 23-hour day
ISO 8601 the standard date text format "2026-10-30T09:30:00Z"
Locale a language-and-region setting for formatting "en-IN" → 30/10/2026
Invalid Date a Date built from text it couldn't read; getTime() is NaN new Date("31/10/2026")
Overflow / roll over out-of-range parts carry into the next unit 35 Oct → 4 Nov

Summary

  • Numbers are binary floating-point: 0.1 + 0.2 is 0.30000000000000004. Round, compare with a tolerance, and keep money in paise.
  • Math.round / floor / ceil / trunc round in different directions; toFixed gives text for display.
  • Math.max(...arr) needs spread. Math.floor(Math.random() * n) gives 0 to n-1; use crypto for anything secret.
  • new Date(y, m, d): months start at 0. setDate(getDate() + n) rolls over months; subtracting dates gives ms.
  • Bad text gives Invalid Date (no error); use YYYY-MM-DD.
  • A Date is one moment in UTC; show it with toLocaleString("en-IN", { timeZone: "Asia/Kolkata" }). Date.now() times code.

Next episode: Map and Set. A visitor list full of duplicates, and a word counter that breaks on the word "constructor".