Chapter 1 of ?
js 15 min read

JavaScript Mastery — Chapter 8: JS Numbers, Math & RegExp

Module 1: JS Fundamentals Chapter 8

Chapter 8: JS Numbers, Math & RegExp

Numbers, mathematical calculations, and regular expressions form the computational heart of JavaScript. Whether calculating financial totals, building randomized game logic, parsing phone numbers, or validating emails with complex regex patterns, this chapter provides complete mastery over precision, math libraries, and pattern matching.


8.1 JavaScript Numbers & 64-Bit Float Architecture

Unlike languages with distinct integer (int, long) and decimal (float, double) types, JavaScript traditionally has only one number type: IEEE 754 double-precision 64-bit binary floating-point.

IEEE 754 64-Bit Float Memory Layout
Sign 1 bit 0: + | 1: - Exponent 11 bits (-1022 to +1023) Scale / Magnitude Fraction / Mantissa 52 bits (53 bits precision with implicit lead 1) Significant Digits (approx 15-17 decimal digits)
The Infamous Floating-Point Precision Quirk

Because computers count in base-2 (binary) rather than base-10 (decimal), fractions like 0.1 (1/10) and 0.2 (1/5) result in infinitely repeating binary fractions. When rounded to 53 significand bits, small rounding errors occur:

Precision Gotcha & Safe Comparison

// 1. The classic surprise
console.log(0.1 + 0.2);            // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);    // false!

// 2. Safe equality check using Number.EPSILON (ES6)
// Number.EPSILON is the difference between 1 and the smallest floating point number > 1 (~2.22e-16)
function areEqual(a, b) {
  return Math.abs(a - b) < Number.EPSILON;
}
console.log(areEqual(0.1 + 0.2, 0.3)); // true!

// 3. Financial calculations best practice:
// Always multiply into whole cents/cents before calculating, then divide:
const totalCents = (10 + 20); // 30 cents
const dollars = totalCents / 100; // $0.30
Try it Yourself »
Safe Integer Range & Special Numbers
Number.MAX_SAFE_INTEGER
Number.MAX_SAFE_INTEGER
// 9,007,199,254,740,991 (2^53 - 1)

Number.isSafeInteger(9007199254740991); // true
Number.isSafeInteger(9007199254740992); // false

Integers beyond this limit cannot be represented uniquely in standard numbers.

Infinity & NaN
console.log(1 / 0);           // Infinity
console.log(-1 / 0);          // -Infinity
console.log(0 / 0);           // NaN ("Not a Number")
console.log(typeof NaN);      // "number" (historic quirk!)
console.log(Number.isNaN(0/0)); // true

Always use Number.isNaN() instead of NaN === NaN (which is false).

8.2 Number Formatting & Conversion Methods

JavaScript provides robust built-in methods on Number.prototype for formatting decimal places, exponential notation, radix conversions, and localized currency display.

Method Description Example Output
.toFixed(digits) Formats a number with a fixed number of decimals, returning a string. (12.3456).toFixed(2) "12.35"
.toPrecision(p) Formats a number to a total number of significant figures (length). (12.3456).toPrecision(3) "12.3"
.toString(radix) Converts number to string in specified base (2=binary, 8=octal, 16=hex). (255).toString(16) "ff"
.toLocaleString() Formats number based on language and currency conventions. (1250000).toLocaleString('en-US') "1,250,000"
Number.isInteger(n) Checks if value is a finite number without a fractional part. Number.isInteger(42.0) true

Converting Strings to Numbers: 4 Techniques

// Technique 1: Number() constructor — strict, fails if any invalid char present
Number("42");        // 42
Number("42.5");      // 42.5
Number("42px");      // NaN (strict!)
Number("");          // 0

// Technique 2: Unary Plus (+) — fastest, equivalent to Number()
+"100";              // 100
+"3.14";             // 3.14
+"invalid";          // NaN

// Technique 3: parseInt(string, radix) — parses leading integer characters
parseInt("42px", 10);     // 42 (stops at 'p')
parseInt("11111111", 2);  // 255 (binary string to decimal number)
parseInt("0xFF", 16);     // 255 (hexadecimal)

// Technique 4: parseFloat(string) — parses leading floating-point decimals
parseFloat("3.14159rem"); // 3.14159

// Modern ES2021: Numeric Separators (syntactic sugar for human readability)
const budget = 1_000_000_000; // 1 billion
const hexMask = 0xFF_AA_00;
Try it Yourself »

8.3 BigInt — Arbitrary Precision Integers

Introduced in ES2020, BigInt is a primitive numeric type that can represent whole numbers of arbitrary precision with no upper limit. It solves the $2^{53} - 1$ limitation for cryptographic tokens, database 64-bit snowflakes, and nanosecond timers.

Creating BigInt
// 1. Suffix with 'n'
const bigLiteral = 9007199254740995n;

// 2. Call BigInt() constructor
const fromStr = BigInt("9007199254740995");
const fromNum = BigInt(42);

console.log(typeof bigLiteral); // "bigint"
Critical BigInt Restrictions
// 1. CANNOT mix BigInt with Number in math
// 10n + 5; // TypeError: Cannot mix BigInt and other types!
const safeSum = 10n + BigInt(5); // 15n

// 2. Math methods do NOT work on BigInt
// Math.max(10n, 20n); // TypeError!

// 3. Division truncates towards 0 (integer division)
console.log(5n / 2n); // 2n (NOT 2.5)

Example: BigInt vs Standard Number Accuracy

// Standard Number overflows beyond 2^53 - 1
console.log(9007199254740991 + 1); // 9007199254740992
console.log(9007199254740991 + 2); // 9007199254740992 (INCORRECT!)

// BigInt calculates exact values with infinite digits
console.log(9007199254740991n + 1n); // 9007199254740992n
console.log(9007199254740991n + 2n); // 9007199254740993n (EXACT!)

// Massive calculations
const factorial20 = 2432902008176640000n;
console.log(factorial20 * 21n); // 51090942171709440000n
Try it Yourself »

8.4 The JavaScript Math Object

The Math object is a static built-in namespace. Unlike Date or RegExp, Math cannot be created with new Math(). All properties and methods are static.

The 4 Rounding Functions: Crucial Differences
Method Positive (4.7) Positive (4.2) Negative (-4.7) Negative (-4.2) Behavior
Math.round(x) 5 4 -5 -4 Rounds to nearest integer (ties round up towards +∞)
Math.floor(x) 4 4 -5 -5 Always rounds down towards -∞
Math.ceil(x) 5 5 -4 -4 Always rounds up towards +∞
Math.trunc(x) 4 4 -4 -4 Truncates decimal portion directly (discards fraction)

Random Numbers & Utility Functions

// 1. Math.random() returns floating-point in range [0, 1) — 0 inclusive, 1 exclusive
console.log(Math.random()); // e.g. 0.49281729182

// 2. Generating random integer between min and max (inclusive)
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 6)); // Dice roll: 1, 2, 3, 4, 5, or 6

// 3. Powers, Roots, and Absolute Values
Math.pow(2, 8);   // 256 (same as 2 ** 8)
Math.sqrt(64);    // 8
Math.cbrt(27);    // 3 (cube root)
Math.abs(-42);    // 42

// 4. Min / Max across array using spread (...)
const scores = [88, 95, 72, 99, 81];
console.log(Math.min(...scores)); // 72
console.log(Math.max(...scores)); // 99
Try it Yourself »

8.5 Regular Expressions (RegExp) Fundamentals

A Regular Expression (RegExp) is an object describing a pattern of characters used to execute text search, validation, and find-and-replace operations with unmatched speed and flexibility.

Anatomy of a JavaScript Regular Expression
/ ^ [a-zA-Z0-9._%+-] + @ [a-zA-Z0-9.-]+ \\. [a-zA-Z]{2,} $ / gi Start Anchor 1 or More Domain Name TLD Extension End / Start / Allowed Chars (Set) Literal @ Escaped Dot End Anchor Flags (Global, i)
Syntax Element Component Pattern Role & Meaning Real-World Example
/ ... / Delimiters Encloses the JavaScript regular expression literal Marks the beginning and end of the pattern body
^ and $ Position Anchors ^ asserts start of string; $ asserts end of string Ensures full-string validation (rejects strings with extra trailing characters)
[a-zA-Z0-9._%+-] Character Class (Set) Matches any single allowed email username character (letters, numbers, ._%+-) Matches s, 9, _, etc.
+ Quantifier Requires 1 or more occurrences of the preceding token Ensures username is not empty (at least 1 character)
@ Literal Separator Matches the exact literal @ symbol separating username from host Separates john.doe from aicodelab.tech
[a-zA-Z0-9.-]+ Domain Name Matches domain name hostnames (letters, digits, dots, hyphens, 1+ characters) Matches aicodelab, gmail, sub.domain
\. Escaped Character Escapes the special wildcard dot . to match a literal period Matches the dot before the domain extension (e.g. . in .com)
[a-zA-Z]{2,} TLD Extension Matches Top-Level Domain extensions consisting of 2 or more letters Matches com, org, tech, edu, ai
gi Regex Flags g (global search: find all matches), i (case-insensitive) Treats user@DOMAIN.COM and user@domain.com identically
1. RegExp Literal
const regex = /pattern/flags;
const re = /javascript/i;

Compiled when the script is loaded. Best performance for static patterns.

2. RegExp Constructor
const query = "hello";
const re = new RegExp(query, "i");

Compiled at runtime. Required when the pattern includes dynamic variables.

The 6 Essential RegExp Flags
Flag Name Functionality
g Global Find all matches across the entire text (does not stop after the first match)
i Ignore Case Case-insensitive search (matches A and a identically)
m Multiline ^ and $ match the start and end of individual lines, not just the whole string
s DotAll Allows the wildcard . to match newline characters (\n)
u Unicode Enables full Unicode surrogate pair matching (essential for emojis and non-Latin scripts)
y Sticky Matches only from the exact index indicated by regex.lastIndex

8.6 Regex Syntax: Classes, Quantifiers & Anchors

Every regular expression is constructed using character classes, sets, quantifiers, and boundaries.

Character Classes

\d → any digit (0-9)

\D → any non-digit

\w → word char (a-z, A-Z, 0-9, _)

\W → non-word char

\s → whitespace (space, tab, newline)

. → any char (except newline)

Quantifiers

+ → 1 or more times

* → 0 or more times

? → 0 or 1 time (optional)

{3} → exactly 3 times

{2,5} → between 2 and 5 times

{3,} → 3 or more times

Anchors & Boundaries

^ → start of string

$ → end of string

\b → word boundary

[abc] → any character in set

[^abc] → any char NOT in set

(a|b) → group with OR

8.7 RegExp Methods in Action

JavaScript RegExp operates through dedicated methods on both the RegExp object and the String prototype.

Regex Execution Methods

// 1. RegExp.prototype.test(str) → Returns true / false (Fastest for validation)
const hasDigits = /\d+/.test("User123"); // true
const isClean = /^[a-z]+$/i.test("Hello World"); // false (has space)

// 2. String.prototype.match(regex) → Returns match array or null
const text = "Contact us at support@aicodelab.tech or sales@aicodelab.tech";
const emails = text.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}/g);
console.log(emails); 
// ["support@aicodelab.tech", "sales@aicodelab.tech"]

// 3. String.prototype.replace(regex, replacement) with capture groups ($1, $2)
const dateStr = "2026-09-13";
const usDate = dateStr.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
console.log(usDate); // "09/13/2026"

// 4. String.prototype.split(regex)
const csv = "Apple, Banana; Orange | Mango";
const fruits = csv.split(/[,;|]\s*/);
console.log(fruits); // ["Apple", "Banana", "Orange", "Mango"]
Try it Yourself »

8.8 Interactive Mini-Labs

Experiment with live JavaScript calculations and regex testing right inside this page.

Lab 1: Number Precision & Rounding Explorer Live Reactive
toFixed(n)
"123.46"
Math.round()
123
Math.floor()
123
Math.ceil()
124
Math.trunc()
123
Binary (Int)
0b1111011
Lab 2: Dynamic Random Range & Dice Simulator
Generated Output
42
Formula: Math.floor(Math.random() * (100 - 1 + 1)) + 1
Lab 3: Interactive Live Regex Matcher & Highlighter
Live Match Highlights: 2 Matches

8.9 Coding Challenge: Input Sanitizer & Formatter

Put your knowledge of Numbers, Math, and RegExp together to build a robust data processor.

Challenge Requirements:
  • Write validatePassword(pass): returns true only if password is ≥ 8 characters, contains at least 1 uppercase letter, 1 lowercase letter, 1 digit, and 1 special symbol ([!@#$%^&*]).
  • Write formatCreditCard(numStr): strips all non-digits and groups into 4 blocks of 4 digits separated by spaces (e.g. "1234 5678 9012 3456").
  • Write calculateCompoundInterest(p, r, t, n): calculates $A = P(1 + \frac{r}{n})^{nt}$, rounded to 2 decimal places using .toFixed(2).

// 1. Password Validator with Positive Lookahead Assertions
function validatePassword(pass) {
  // (?=.*[a-z]) : at least one lowercase
  // (?=.*[A-Z]) : at least one uppercase
  // (?=.*\d)     : at least one digit
  // (?=.*[!@#$%^&*]) : at least one special char
  // .{8,}       : at least 8 characters long
  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;
  return regex.test(pass);
}

// 2. Credit Card Formatter
function formatCreditCard(numStr) {
  const digitsOnly = numStr.replace(/\D/g, ""); // Strip non-digits
  return digitsOnly.replace(/(\d{4})(?=\d)/g, "$1 "); // Group in 4s
}

// 3. Compound Interest Calculator
function calculateCompoundInterest(principal, ratePercent, years, timesCompoundedPerYear) {
  const r = ratePercent / 100;
  const amount = principal * Math.pow(1 + (r / timesCompoundedPerYear), timesCompoundedPerYear * years);
  return amount.toFixed(2);
}

// Verification Tests
console.log(validatePassword("P@ssw0rd123")); // true
console.log(validatePassword("simple123"));   // false (no uppercase, no special)
console.log(formatCreditCard("4532-8921-7643-9821")); // "4532 8921 7643 9821"
console.log(calculateCompoundInterest(1000, 5, 10, 12)); // "1647.01"

8.10 Chapter Summary & Key Takeaways

Numbers & Math Rules
  • All standard numbers are 64-bit float (IEEE 754).
  • 0.1 + 0.2 === 0.30000000000000004; compare with Number.EPSILON.
  • Safe integer limit is $2^{53}-1$; use BigInt for arbitrary precision.
  • Math.floor() rounds down; Math.trunc() strips the decimal.
RegExp Rules
  • Use literals /re/ for static patterns, new RegExp() for dynamic variables.
  • test() returns boolean; matchAll() returns full match groups.
  • ^ and $ anchor to string start/end; \b anchors to word boundaries.
  • g flag enables global matching across all occurrences.
Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *