JavaScript · Lesson 8 of 15
Strings, Numbers and Math
String methods, number quirks, parsing and the Math object.
- Beginner
- 12 min read
- 3 objectives
Before this lessonLesson 7: Conditionals and Loops
What you will learn
- Use common string methods
- Parse and format numbers
- Handle floating-point surprises
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 3 hours
Create a free account to keep your progress on every device.
Strings and numbers look simple, but a handful of methods and one famous floating-point quirk cover most day-to-day surprises.
String methods
const s = " Hello, World ";
console.log(s.trim());
console.log(s.trim().toUpperCase());
console.log(s.includes("World"));
console.log(s.trim().slice(0, 5));
console.log("a-b-c".split("-"));
console.log("ha".repeat(3));
console.log("7".padStart(3, "0"));
console.log("abc".replaceAll("b", "X"));Output
Hello, World HELLO, WORLD true Hello [ 'a', 'b', 'c' ] hahaha 007 aXc
Strings are immutable: these methods return new strings and leave the original alone.
Numbers
JavaScript has one number type (a 64-bit float) plus BigInt for huge integers. That means decimals are approximate.
console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));
console.log(Math.abs(0.3 - (0.1 + 0.2)) < Number.EPSILON);
console.log(parseInt("42px"), Number("42px"));
console.log(Number.isInteger(5.0));Output
0.30000000000000004 0.30 true 42 NaN true
The Math object
console.log(Math.round(2.5), Math.floor(2.9), Math.ceil(2.1));
console.log(Math.max(3, 9, 4), Math.min(3, 9, 4));
console.log(Math.max(...[5, 1, 8]));
const dice = Math.floor(Math.random() * 6) + 1;
console.log(dice >= 1 && dice <= 6);Output
3 2 3 9 3 8 true
Formatting for people
console.log((1234567.891).toLocaleString("en-US"));
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(19.5));Output
Objects, this and PrototypesObject literals, methods, this binding and how prototypes share behaviour.
1,234,567.891 $19.50
