Strings & Numbers
template literals, string/math methods
Skills taught: js.strings, js.numbers, js.template-literals, js.math
Template literals
const name = 'Prashant';
const score = 95;
// Template literal — backticks, ${} for interpolation
const message = `Hello, ${name}! Your score is ${score}.`;
const grade = `Grade: ${score >= 90 ? 'A' : 'B'}`;
// Multi-line string
const html = `
<div class="card">
<h2>${name}</h2>
<p>Score: ${score}</p>
</div>
`;
console.log(message); // 'Hello, Prashant! Your score is 95.'
Essential string methods
const str = ' Hello, World! ';
str.length // 18
str.trim() // 'Hello, World!' (remove whitespace)
str.toUpperCase() // ' HELLO, WORLD! '
str.toLowerCase() // ' hello, world! '
str.includes('World') // true
str.startsWith(' H') // true
str.indexOf('World') // 9
str.slice(2, 7) // 'Hello'
str.replace('World', 'KERNAL') // ' Hello, KERNAL! '
str.split(', ') // [' Hello', 'World! ']
str.trim().split(', ') // ['Hello', 'World!']
// Padding — useful for formatting tables
'7'.padStart(3, '0') // '007'
'Hi'.padEnd(10, '-') // 'Hi--------'
Number methods and Math
// Parsing strings to numbers
parseInt('42px') // 42 — stops at non-digit
parseFloat('3.14abc') // 3.14
Number('42') // 42 — strict, returns NaN for invalid
Number('42px') // NaN
+'42' // 42 — unary + operator (shorthand)
// Formatting output
(3.14159).toFixed(2) // '3.14' — returns a STRING
(1234567).toLocaleString() // '1,234,567' (locale-aware)
// Math object
Math.round(4.6) // 5
Math.floor(4.9) // 4 — always rounds down
Math.ceil(4.1) // 5 — always rounds up
Math.abs(-5) // 5 — absolute value
Math.max(1,5,3) // 5
Math.min(1,5,3) // 1
Math.random() // 0 to 0.9999... (never 1)
Math.PI // 3.14159...
Math.sqrt(16) // 4
// Random integer between min and max (inclusive)
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
rand(1, 6); // simulates a dice roll
Frequently Asked Questions
What is the difference between slice() and substring()?
Both extract a part of a string. slice() accepts negative indices (str.slice(-3) gets the last 3 characters). substring() treats negative indices as 0. slice() is generally preferred.
How do I convert a number to a string?
String(42) or (42).toString() or template literal `${42}`. The unary + operator converts string to number: +'42' === 42.