Built-in Methods and Math
Topic: Foundations (Extended)
Concepts Covered: String methods, Number methods, Math object
String Built-in Methods
Section titled “String Built-in Methods”JavaScript provides many built-in methods to work with strings effectively.
String Creation
Section titled “String Creation”let str1 = "Hello, World!";let str2 = "JavaScript";let str3 = `Template literal with ${str1}`;Essential String Properties and Methods
Section titled “Essential String Properties and Methods”Length Property
Section titled “Length Property”let text = "Hello, World!";console.log(text.length); // 13Case Conversion
Section titled “Case Conversion”let text = "Hello, World!";
console.log(text.toUpperCase()); // "HELLO, WORLD!"console.log(text.toLowerCase()); // "hello, world!"console.log(text); // Original unchanged: "Hello, World!"Finding and Searching
Section titled “Finding and Searching”let text = "Hello, World!";
// indexOf() - returns index of first occurrenceconsole.log(text.indexOf("World")); // 7console.log(text.indexOf("world")); // -1 (case sensitive)console.log(text.indexOf("o")); // 4 (first occurrence)
// lastIndexOf() - returns index of last occurrenceconsole.log(text.lastIndexOf("o")); // 8
// includes() - check if string contains substringconsole.log(text.includes("World")); // trueconsole.log(text.includes("world")); // false
// startsWith() and endsWith()console.log(text.startsWith("Hello")); // trueconsole.log(text.endsWith("!")); // trueExtracting Parts of Strings
Section titled “Extracting Parts of Strings”let text = "Hello, World!";
// substring() - extract between two indicesconsole.log(text.substring(0, 5)); // "Hello"console.log(text.substring(7, 12)); // "World"
// slice() - similar to substring but can handle negative indicesconsole.log(text.slice(0, 5)); // "Hello"console.log(text.slice(-6, -1)); // "World"console.log(text.slice(7)); // "World!" (from index 7 to end)
// charAt() - get character at specific indexconsole.log(text.charAt(0)); // "H"console.log(text.charAt(7)); // "W"Modifying Strings
Section titled “Modifying Strings”let text = "Hello, World!";
// replace() - replace first occurrenceconsole.log(text.replace("World", "Universe")); // "Hello, Universe!"console.log(text.replace("o", "0")); // "Hell0, World!" (only first occurrence)
// replaceAll() - replace all occurrencesconsole.log(text.replaceAll("o", "0")); // "Hell0, W0rld!"
// split() - split string into arrayconsole.log(text.split(",")); // ["Hello", " World!"]console.log(text.split("")); // ["H", "e", "l", "l", "o", ..., "!"]console.log("apple,banana,cherry".split(",")); // ["apple", "banana", "cherry"]
// trim() - remove whitespace from both endslet spacedText = " Hello, World! ";console.log(spacedText.trim()); // "Hello, World!"Practical String Example: Palindrome Checker
Section titled “Practical String Example: Palindrome Checker”function isPalindrome(str) { // Clean the string: lowercase and remove non-alphanumeric characters const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, "");
// Split into array, reverse, and join back const reversed = cleaned.split("").reverse().join("");
// Compare original with reversed return cleaned === reversed;}
// Test casesconst testCases = ["racecar", "rotator", "books", "radar", "leader", "noon"];const results = testCases.map(isPalindrome);console.log(results); // [true, true, false, true, false, true]
console.log(isPalindrome("A man a plan a canal Panama")); // trueconsole.log(isPalindrome("race a car")); // falseNumber Built-in Methods
Section titled “Number Built-in Methods”Number Creation and Conversion
Section titled “Number Creation and Conversion”let num1 = 10;let num2 = 3.14159;let stringNum = "42";
// Convert string to numberconsole.log(parseInt("10")); // 10 (integer)console.log(parseInt("10.5")); // 10 (cuts off decimal)console.log(parseFloat("3.14")); // 3.14 (keeps decimal)console.log(Number("42")); // 42 (converts entire string)
// Check if value is a numberconsole.log(Number.isNaN(NaN)); // trueconsole.log(Number.isNaN("hello")); // false (it's not NaN, it's a string)console.log(isNaN("hello")); // true (tries to convert first)Number Formatting
Section titled “Number Formatting”let num = 3.14159;
// toFixed() - format to specific decimal placesconsole.log(num.toFixed(2)); // "3.14" (string)console.log(num.toFixed(0)); // "3" (string)
// toString() - convert number to stringconsole.log(num.toString()); // "3.14159"
// toPrecision() - format to specific number of significant digitsconsole.log(num.toPrecision(3)); // "3.14"console.log((1234).toPrecision(3)); // "1.23e+3"Math Object
Section titled “Math Object”The Math object provides mathematical constants and functions.
Math Constants
Section titled “Math Constants”console.log(Math.PI); // 3.141592653589793console.log(Math.E); // 2.718281828459045Basic Math Methods
Section titled “Basic Math Methods”// Absolute valueconsole.log(Math.abs(-5)); // 5console.log(Math.abs(5)); // 5
// Rounding methodsconsole.log(Math.ceil(3.14)); // 4 (round up)console.log(Math.floor(3.14)); // 3 (round down)console.log(Math.round(3.14)); // 3 (round to nearest)console.log(Math.round(3.64)); // 4
// Min and Maxconsole.log(Math.max(1, 2, 3, 4, 5)); // 5console.log(Math.min(1, 2, 3, 4, 5)); // 1console.log(Math.max(...[1, 2, 3, 4, 5])); // 5 (using spread operator)
// Power and square rootconsole.log(Math.pow(2, 3)); // 8 (2 to the power of 3)console.log(Math.sqrt(16)); // 4 (square root of 16)console.log(Math.cbrt(27)); // 3 (cube root of 27)Random Numbers
Section titled “Random Numbers”// Math.random() returns a number between 0 (inclusive) and 1 (exclusive)console.log(Math.random()); // e.g., 0.123456789
// Random integer between min and max (inclusive)function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;}
console.log(randomInt(1, 6)); // Random number between 1 and 6 (dice roll)console.log(randomInt(10, 20)); // Random number between 10 and 20
// Random element from arrayfunction randomElement(array) { return array[Math.floor(Math.random() * array.length)];}
let colors = ["red", "blue", "green", "yellow"];console.log(randomElement(colors)); // Random colorAdvanced Math Methods
Section titled “Advanced Math Methods”// Trigonometric functions (work with radians)console.log(Math.sin(Math.PI / 2)); // 1 (sin of 90 degrees)console.log(Math.cos(0)); // 1 (cos of 0 degrees)
// Logarithmic functionsconsole.log(Math.log(Math.E)); // 1 (natural logarithm)console.log(Math.log10(100)); // 2 (base-10 logarithm)
// Sign functionconsole.log(Math.sign(-5)); // -1console.log(Math.sign(5)); // 1console.log(Math.sign(0)); // 0Practical Examples
Section titled “Practical Examples”Temperature Converter
Section titled “Temperature Converter”function celsiusToFahrenheit(celsius) { return Math.round((celsius * 9) / 5 + 32);}
function fahrenheitToCelsius(fahrenheit) { return Math.round(((fahrenheit - 32) * 5) / 9);}
console.log(celsiusToFahrenheit(25)); // 77°Fconsole.log(fahrenheitToCelsius(77)); // 25°CPassword Generator
Section titled “Password Generator”function generatePassword(length = 8) { const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*"; let password = "";
for (let i = 0; i < length; i++) { password += chars.charAt(Math.floor(Math.random() * chars.length)); }
return password;}
console.log(generatePassword()); // Random 8-character passwordconsole.log(generatePassword(12)); // Random 12-character passwordText Statistics
Section titled “Text Statistics”function textStats(text) { const words = text.trim().split(/\s+/); const sentences = text.split(/[.!?]+/).filter((s) => s.trim().length > 0); const vowels = text.match(/[aeiouAEIOU]/g) || [];
return { characters: text.length, charactersNoSpaces: text.replace(/\s/g, "").length, words: words.length, sentences: sentences.length, vowels: vowels.length, averageWordsPerSentence: Math.round((words.length / sentences.length) * 100) / 100, };}
let text = "Hello world! How are you today? This is a test.";console.log(textStats(text));Number Formatter
Section titled “Number Formatter”function formatNumber(num, decimals = 2) { return num.toLocaleString("en-US", { minimumFractionDigits: decimals, maximumFractionDigits: decimals, });}
function formatCurrency(amount, currency = "USD") { return new Intl.NumberFormat("en-US", { style: "currency", currency: currency, }).format(amount);}
console.log(formatNumber(1234.567)); // "1,234.57"console.log(formatCurrency(1234.56)); // "$1,234.56"console.log(formatCurrency(1234.56, "EUR")); // "€1,234.56"Best Practices
Section titled “Best Practices”- Chain string methods carefully: Remember each method returns a new string
- Use appropriate rounding:
Math.round(),Math.ceil(), orMath.floor()based on needs - Handle edge cases: Check for empty strings, NaN, etc.
- Use
Number.isNaN()instead ofisNaN(): More reliable type checking - Remember Math.random() range: 0 (inclusive) to 1 (exclusive)
Common Pitfalls
Section titled “Common Pitfalls”- String methods return new strings: Original string is unchanged
- Case sensitivity: “Hello” !== “hello”
- parseInt() with leading zeros: Can be interpreted as octal
- Floating point precision: 0.1 + 0.2 !== 0.3 exactly
Key Takeaways
Section titled “Key Takeaways”- String methods: Powerful tools for text manipulation
- Math object: Essential for mathematical operations
- Immutable strings: Methods return new strings, don’t modify originals
- Random numbers: Use Math.random() with Math.floor() for integers
- Number formatting: Use toFixed() for decimal places, toLocaleString() for locale-specific formatting
Practice Exercises
Section titled “Practice Exercises”- Create a function that counts words, sentences, and paragraphs in text
- Build a string cipher that shifts letters by a certain amount
- Write a function that validates email addresses using string methods
- Create a random quote generator
- Build a simple calculator using Math methods