JavaScript Strings, Numbers & Math Explained — Complete Practical Guide
Strings, numbers, and dates are the most common data types in everyday JavaScript — you’ll manipulate text, perform calculations, and handle dates in almost every program you write.
What You’ll Learn
- String methods for searching, slicing, and transforming text
- Template literals for cleaner string formatting
- Number quirks: floating-point precision, NaN, BigInt
- Math operations and random number generation
- Date creation, formatting, and manipulation
- Common pitfalls with type coercion and immutability
Why Strings, Numbers & Math Matters
Every application processes text and numbers. The Doda Browser parses URLs (strings), calculates memory usage (numbers), and timestamps downloads (dates). The Durga Antivirus Pro dashboard displays scan statistics, formats file sizes, and shows last-scan dates. Even a simple form needs to validate email addresses (string methods), calculate totals (math), and record submission times (dates).
Security note: Understanding Js Strings Numbers helps build more secure applications — a core principle at DodaTech, where tools like Durga Antivirus Pro and Doda Browser rely on solid implementation practices.
Learning Path
flowchart LR
A[JavaScript Basics] --> B[Operators & Control Flow]
B --> C[Strings, Numbers & Math]
C --> D[Arrays]
C --> E[JSON]
C --> F[You Are Here]
typeof is helpful for distinguishing strings from numbers.Strings: Working with Text
A string is a sequence of characters — letters, numbers, symbols, or spaces — enclosed in quotes. Think of it like a string of beads, each bead being one character.
Creating Strings
const single = 'Hello'; // Single quotes
const double = "Hello"; // Double quotes — same thing
const backtick = `Hello`; // Template literal — most powerful
Which should you use? Template literals (backticks) are the most flexible. They support interpolation (embedding variables) and multi-line strings.
Template Literals
const name = 'Alice';
const age = 25;
// Embedding variables with ${}
const message = `Hello, ${name}! You are ${age} years old.`;
console.log(message); // 'Hello, Alice! You are 25 years old.'
// Multi-line without \n
const html = `
<div>
<h1>${name}</h1>
</div>
`;Why template literals win: Without them, you’d write 'Hello, ' + name + '! You are ' + age + ' years old.' — messy and error-prone. The ${} syntax is like filling blanks in a form.
Essential String Methods
Strings are immutable — methods return a new string without changing the original:
const str = ' Hello, World! ';
console.log(str.length); // 17 — count characters (includes spaces)
console.log(str.toUpperCase()); // ' HELLO, WORLD! ' — new string, all caps
console.log(str.toLowerCase()); // ' hello, world! ' — new string, all lower
console.log(str.trim()); // 'Hello, World!' — removes whitespace from both ends
console.log(str.trimStart()); // 'Hello, World! ' — removes leading whitespace
console.log(str.indexOf('World')); // 8 — position where 'World' starts (0-based)
console.log(str.includes('Hello')); // true — does it contain 'Hello'?
console.log(str.slice(2, 7)); // 'Hello' — extracts characters from index 2 to 6
console.log(str.replace('World', 'JS')); // ' Hello, JS! ' — replaces first match
Line by line explanation:
str.length— Property (not a method) that gives the total character count.str.trim()— Useful for cleaning user input from forms where users accidentally add spaces.str.indexOf('World')— Returns8because'World'starts at the 9th character (0-indexed). Returns-1if not found.str.slice(2, 7)— Extract characters from index 2 up to (but not including) index 7.
Anticipating confusion: Why is slice(2, 7) returning characters at indices 2, 3, 4, 5, 6 but not 7? Because slice is end-exclusive — it stops before the end index. Think of it as “start at 2, take 5 characters.”
Numbers: Integers, Floats, and Quirks
JavaScript has one number type for all numeric values — Number. It handles both integers and decimals:
const int = 42; // Integer
const float = 3.14; // Floating-point (decimal)
const neg = -10; // Negative
const exp = 1.5e6; // 1,500,000 (scientific notation)
The Floating-Point Problem
console.log(0.1 + 0.2); // 0.30000000000000004 — not 0.3!
Why? Computers store numbers in binary (base 2). Just like 1/3 can’t be exactly represented in decimal (0.333…), 0.1 can’t be exactly represented in binary. This is not a JavaScript bug — it affects every programming language.
Fix: Use toFixed() for display rounding:
console.log((0.1 + 0.2).toFixed(1)); // '0.3'
NaN and Infinity
console.log(Number('hello')); // NaN — Not a Number
console.log(typeof NaN); // 'number' — confusing but true!
console.log(1 / 0); // Infinity
// Check for NaN properly
console.log(Number.isNaN(NaN)); // true
console.log(isNaN('hello')); // true — but converts type first
Anticipating confusion: typeof NaN returns "number". That sounds wrong, but NaN is a numeric value meaning “this calculation produced something that isn’t a number.” Always use Number.isNaN() to check for it.
Number Conversion
console.log(Number('42')); // 42
console.log(+'42'); // 42 — unary plus (shorthand)
console.log(Number('42px')); // NaN — fails!
console.log(parseInt('42px')); // 42 — parses until non-digit
console.log(parseFloat('3.14em')); // 3.14
Rule of thumb: Use Number() for strict conversion (strings must be purely numeric). Use parseInt()/parseFloat() for strings that may have trailing units like '42px'.
BigInt
For numbers larger than 9007199254740991 (Number.MAX_SAFE_INTEGER):
const big = 9007199254740991n; // n suffix
const huge = BigInt('12345678901234567890');
console.log(big + 1n); // 9007199254740992n
console.log(big / 2n); // 4503599627370495n (truncates, no decimals)
// console.log(big + 1); // TypeError! Can't mix BigInt and Number
When to use BigInt: Financial calculations, large IDs from databases, precise integer arithmetic beyond 2⁵³.
Math Object
The Math object provides mathematical constants and functions:
console.log(Math.round(4.7)); // 5 — nearest integer
console.log(Math.ceil(4.2)); // 5 — round UP
console.log(Math.floor(4.9)); // 4 — round DOWN
console.log(Math.trunc(4.9)); // 4 — remove decimals (same as floor for positive)
console.log(Math.max(1, 5, 3)); // 5 — largest value
console.log(Math.min(1, 5, 3)); // 1 — smallest value
console.log(Math.pow(2, 10)); // 1024 — 2¹⁰
console.log(Math.sqrt(81)); // 9 — square root
console.log(Math.abs(-5)); // 5 — absolute value
console.log(Math.PI); // 3.141592653589793
Random Numbers
console.log(Math.random()); // 0.0 to 0.999...
console.log(Math.floor(Math.random() * 10) + 1); // Integer 1 to 10
How the random formula works:
Math.random()gives 0 to 0.999* 10gives 0 to 9.999Math.floor()gives 0 to 9+ 1gives 1 to 10
Date
Creating Dates
const now = new Date(); // Current date/time
const specific = new Date(2024, 0, 15); // January 15, 2024 — month is 0-indexed!
const fromStr = new Date('2024-01-15'); // String format — month is 1-indexed
const timestamp = Date.now(); // Milliseconds since Jan 1, 1970
Critical: Months are 0-indexed. new Date(2024, 0, 1) is January 1, not December 1. This is a common source of bugs.
Getting and Setting Values
const d = new Date('2024-03-15T10:30:00');
console.log(d.getFullYear()); // 2024
console.log(d.getMonth()); // 2 (March — 0-indexed)
console.log(d.getDate()); // 15
console.log(d.getDay()); // 5 (Friday — 0=Sunday, 6=Saturday)
console.log(d.getHours()); // 10
console.log(d.getMinutes()); // 30
d.setFullYear(2025);
d.setMonth(11); // December
d.setDate(25);Formatting Dates
console.log(d.toISOString()); // '2025-12-25T10:30:00.000Z'
console.log(d.toLocaleDateString('en-US')); // '12/25/2025'
console.log(d.toLocaleDateString('en-GB')); // '25/12/2025'
Common Mistakes
1. Strings are immutable
let str = 'hello';
str[0] = 'H'; // No error, but doesn't work
str = str.toUpperCase(); // Must reassign — returns a new string
2. Floating-point precision issues
console.log(0.1 + 0.2 === 0.3); // false!
Fix: Use toFixed() for display or a tolerance for comparison: Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON.
3. Using new Number() or new String()
console.log(typeof new Number(5)); // 'object'
console.log(typeof Number(5)); // 'number'
Primitives are faster and simpler. Use literals, not wrapper objects.
4. Months are 0-indexed in Date constructor
new Date(2024, 0, 1); // January 1 — correct!
new Date(2024, 11, 1); // December 1
But new Date('2024-01-15') uses 1-indexed months!
5. Confusing + for strings vs numbers
console.log('5' + 3); // '53' — string concatenation
console.log('5' - 3); // 2 — numeric subtraction
The + operator prefers string concatenation when either operand is a string.
6. Using Number() vs parseInt() incorrectly
Number('42px'); // NaN
parseInt('42px'); // 42
Practice Questions
What does
'Hello'.slice(1, 3)return?'el'— starts at index 1, ends before index 3 (end-exclusive).Why does
0.1 + 0.2 !== 0.3? Floating-point representation in binary can’t exactly represent 0.1 or 0.2.What’s the difference between
Number()andparseInt()?Number()requires a purely numeric string.parseInt()parses until a non-digit character.How do you generate a random integer between 5 and 10?
Math.floor(Math.random() * 6) + 5
Challenge: Build a function formatDate(date) that takes a Date object and returns a string like “March 15, 2024”. Then extend it to show “March 15, 2024, 10:30 AM”.
FAQ
Try It Yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Strings & Numbers Playground</title>
<style>
body { font-family: Arial, sans-serif; padding: 2rem; }
pre { background: #f4f4f4; padding: 1rem; border-radius: 5px; }
</style>
</head>
<body>
<h1>Strings & Numbers Sandbox</h1>
<pre id="output"></pre>
<script>
const out = document.getElementById('output');
let result = '';
// String operations
const name = 'Alice';
result += `Upper: ${name.toUpperCase()}\n`;
result += `Length: ${name.length}\n`;
result += `Template: Hello, ${name}!\n\n`;
// Number operations
const price = 19.99;
const tax = 0.08;
const total = price * (1 + tax);
result += `Price: $${price}\n`;
result += `Tax: ${tax * 100}%\n`;
result += `Total: $${total.toFixed(2)}\n\n`;
// Random number
const random = Math.floor(Math.random() * 100) + 1;
result += `Random (1-100): ${random}\n`;
// Date
const now = new Date();
result += `Today: ${now.toLocaleDateString('en-US')}\n`;
result += `Time: ${now.toLocaleTimeString('en-US')}`;
out.textContent = result;
</script>
</body>
</html>What’s Next
Now that you can manipulate text and numbers, move on to structured data:
| Lesson | Description |
|---|---|
| JavaScript Home | Back to the JavaScript hub |
| https://tutorials.dodatech.com/programming-languages/javascript/js-arrays/ | Arrays — ordered collections of data |
| https://tutorials.dodatech.com/programming-languages/javascript/js-json/ | JSON — working with data exchange format |
| https://tutorials.dodatech.com/programming-languages/javascript/js-functions/ | Functions & Scope |
| CSS Styling | Style your text output on the page |
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
What’s Next
Congratulations on completing this Js Strings Numbers tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro