🔢 Working with Data: Numbers and Math in JavaScript
The Story of Numbers in Code
Imagine you have a magical calculator. But this isn’t any ordinary calculator—it lives inside your computer and can do things regular calculators can only dream of! This magical calculator is how JavaScript handles numbers.
Let’s go on an adventure to discover all the cool things we can do with numbers!
🎯 Number Literals and Precision
What Are Number Literals?
A number literal is just a fancy way of saying “a number you type directly into your code.”
Think of it like this: When you write your age on a form, you just write “10” or “25”. That’s a literal—you’re literally writing the number!
let age = 10; // Integer
let price = 19.99; // Decimal
let million = 1e6; // Scientific: 1,000,000
let tiny = 5e-3; // Scientific: 0.005
The Precision Problem
Here’s a surprise: computers aren’t perfect at math with decimals!
0.1 + 0.2
// Expected: 0.3
// Actual: 0.30000000000000004 😱
Why? Computers think in 1s and 0s. Some decimals can’t be stored perfectly—like trying to write ⅓ as a decimal (0.333333… forever).
Pro Tip: For money, multiply by 100, work with cents, then divide back!
// ❌ Dangerous
0.1 + 0.2 // 0.30000000000000004
// ✅ Safe
(10 + 20) / 100 // 0.3
🌀 NaN and Infinity
NaN: Not a Number
NaN stands for “Not a Number.” It’s JavaScript’s way of saying “I tried to do math, but this doesn’t make sense!”
"hello" * 5 // NaN
Math.sqrt(-1) // NaN
0 / 0 // NaN
The Weird Part: NaN is not equal to itself!
NaN === NaN // false 🤯
Use Number.isNaN() to check:
Number.isNaN(NaN) // true
Number.isNaN("hello") // false
Infinity: Beyond All Numbers
When numbers get too big or you divide by zero:
1 / 0 // Infinity
-1 / 0 // -Infinity
Number.MAX_VALUE * 2 // Infinity
Check for it:
Number.isFinite(100) // true
Number.isFinite(Infinity) // false
🔧 Number Parsing Functions
Turning Text into Numbers
Sometimes you get numbers as text (like from a form). You need to convert them!
parseInt("42") // 42
parseInt("42.9") // 42 (cuts off decimal)
parseFloat("42.9") // 42.9 (keeps decimal)
parseInt("42abc") // 42 (stops at letter)
parseInt("abc42") // NaN (starts with letter)
The Radix Secret
parseInt has a second power—reading different number systems!
parseInt("1010", 2) // 10 (binary)
parseInt("FF", 16) // 255 (hexadecimal)
parseInt("77", 8) // 63 (octal)
Always specify radix 10 for normal numbers:
parseInt("08", 10) // 8 ✅
✅ Number Checking Methods
Is This Really a Number?
// Safe integer check
Number.isInteger(5) // true
Number.isInteger(5.0) // true
Number.isInteger(5.5) // false
// Safe integer range check
Number.isSafeInteger(5) // true
Number.isSafeInteger(9007199254740992) // false
// NaN check
Number.isNaN(NaN) // true
Number.isNaN("NaN") // false
// Finite check
Number.isFinite(100) // true
Number.isFinite(Infinity) // false
The Safe Zone
JavaScript can safely handle integers up to:
Number.MAX_SAFE_INTEGER // 9007199254740991
Number.MIN_SAFE_INTEGER // -9007199254740991
Beyond this, weird things happen:
9007199254740992 === 9007199254740993 // true 😱
🎨 Number Formatting Methods
Making Numbers Pretty
toFixed() - Control Decimals
(3.14159).toFixed(2) // "3.14"
(3.1).toFixed(3) // "3.100"
(3).toFixed(2) // "3.00"
toPrecision() - Control Total Digits
(123.456).toPrecision(4) // "123.5"
(123.456).toPrecision(2) // "1.2e+2"
toLocaleString() - Human-Friendly Format
(1000000).toLocaleString()
// "1,000,000" (US)
(1234.5).toLocaleString('de-DE')
// "1.234,5" (German)
toString() - Convert to String
(255).toString() // "255"
(255).toString(16) // "ff" (hex)
(255).toString(2) // "11111111" (binary)
🧮 Math Object Methods
The Math Toolbox
The Math object is like a Swiss Army knife for numbers!
Rounding Family
Math.round(4.5) // 5 (nearest)
Math.round(4.4) // 4
Math.floor(4.9) // 4 (always down)
Math.ceil(4.1) // 5 (always up)
Math.trunc(4.9) // 4 (cut decimal)
Math.trunc(-4.9) // -4
Power & Roots
Math.pow(2, 3) // 8 (2³)
Math.sqrt(16) // 4 (√16)
Math.cbrt(27) // 3 (∛27)
Finding Extremes
Math.max(1, 5, 3) // 5
Math.min(1, 5, 3) // 1
Math.abs(-5) // 5 (distance from 0)
Random Numbers
Math.random() // 0 to 0.999...
// Random integer 1-10
Math.floor(Math.random() * 10) + 1
Trigonometry (for games & graphics)
Math.sin(0) // 0
Math.cos(0) // 1
Math.tan(Math.PI/4) // ~1
Logarithms
Math.log(Math.E) // 1 (natural log)
Math.log10(100) // 2
Math.log2(8) // 3
📏 Math Constants
The Magic Numbers
Math.PI // 3.141592653589793
Math.E // 2.718281828459045
Math.LN2 // 0.693... (ln 2)
Math.LN10 // 2.302... (ln 10)
Math.LOG2E // 1.442... (log₂ e)
Math.LOG10E // 0.434... (log₁₀ e)
Math.SQRT2 // 1.414... (√2)
Math.SQRT1_2 // 0.707... (1/√2)
Circle Example:
let radius = 5;
let circumference = 2 * Math.PI * radius;
// 31.41592653589793
🐘 BigInt Operations
When Numbers Aren’t Big Enough
Regular JavaScript numbers have limits. But what if you need REALLY big numbers?
Enter BigInt—for numbers as big as your imagination!
// Regular number limit
9007199254740991 // MAX_SAFE_INTEGER
// BigInt to the rescue!
9007199254740992n // Add 'n' at the end
BigInt("99999999999999999999999999")
BigInt Rules
// Arithmetic works!
10n + 5n // 15n
10n * 3n // 30n
10n / 3n // 3n (no decimals!)
// ❌ Can't mix with regular numbers
10n + 5 // TypeError!
// ✅ Convert first
10n + BigInt(5) // 15n
Number(10n) + 5 // 15
// Comparisons work
10n > 5 // true
10n === 10 // false (different types)
10n == 10 // true (loose equality)
When to Use BigInt
- Cryptography
- Very large IDs
- Scientific calculations
- When precision matters for big integers
// Giant factorial
function factorial(n) {
if (n <= 1n) return 1n;
return n * factorial(n - 1n);
}
factorial(50n)
// 30414093201713378043612608166064...n
🎓 Quick Summary
graph LR A[JavaScript Numbers] --> B[Literals & Precision] A --> C[Special Values] A --> D[Parsing] A --> E[Checking] A --> F[Formatting] A --> G[Math Object] A --> H[BigInt] B --> B1[Integers & Decimals] B --> B2[Scientific Notation] C --> C1[NaN] C --> C2[Infinity] G --> G1[Rounding] G --> G2[Random] G --> G3[Trig]
🚀 You Did It!
You now know how to:
- ✅ Write number literals
- ✅ Handle NaN and Infinity
- ✅ Parse strings to numbers
- ✅ Check number types safely
- ✅ Format numbers beautifully
- ✅ Use the Math toolbox
- ✅ Work with Math constants
- ✅ Go BIG with BigInt
Numbers in JavaScript are powerful! With these tools, you can build calculators, games, scientific apps, and so much more.
Happy coding! 🎉