JavaScript
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Types
-
Section 3: Strings and Numbers in Depth
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Objects and Arrays
-
Section 7: Maps, Sets, and Symbols
-
Section 8: Asynchronous JavaScript
-
Section 9: Object-Oriented and Prototypes
-
Section 10: The DOM
-
Section 11: Browser APIs
-
Section 12: Modern JavaScript (ES2015-ES2025)
-
Section 13: Functional Programming Patterns
-
Section 14: Error Handling and Debugging
-
Section 15: Testing
-
Section 16: Accessibility for JavaScript Developers
-
Section 17: Internationalization and Localization
-
Section 18: Performance
-
Section 19: Node.js Fundamentals
-
Section 20: Regular Expressions
-
Section 21: Design Patterns in JavaScript
-
Section 22: Security Basics
-
Section 23: Data Structures and Algorithms in JavaScript
-
Section 24: Practical Projects
-
Section 25: More Advanced Async Patterns
-
Section 26: More Object and Class Practice
-
Section 27: Working with Dates and Internationalization
-
Section 28: Web Components
-
Section 29: More DOM and Browser Practice
-
Section 30: Build Tooling for Vanilla JavaScript
-
Section 31: More Practice Projects
-
Section 32: Interview and Algorithm Practice
-
Section 33: Error Objects (MDN Reference)
-
Section 34: TypedArrays and Binary Data
-
Section 35: Reflection and Metaprogramming (MDN Reference)
-
Section 36: More Global Functions (MDN Reference)
247: parseInt and parseFloat Edge Cases
You've likely used parseInt and parseFloat a hundred times by now, but in a real production environment, you aren't dealing with clean numbers. You're dealing with user input, which is notoriously messy. I want to show you how these functions behave when things get weird, because if you don't account for the edge cases, you'll end up with NaN poisoning your entire data set.
Parsing "Dirty" Price Strings
Let's say we're building a small checkout utility. Users often type things like "$49.99" or "100 USD" into a field. I want a function that extracts the numeric value regardless of the trailing text. I'll start by writing a quick helper to handle the price.
function parsePrice(input) {
return parseInt(input);
}
console.log(parsePrice("49.99 USD")); // 49
console.log(parsePrice("100")); // 100
Wait. I just caught a huge mistake. I used parseInt for a price. If a user enters "49.99", I'm effectively stealing 99 cents from them (or losing it) because parseInt stops the moment it hits a decimal point. It doesn't round; it truncates. For any currency or measurement, parseFloat is the only way to go.
function parsePrice(input) {
// I'm switching to parseFloat to keep those decimals
return parseFloat(input);
}
console.log(parsePrice("49.99 USD")); // 49.99
console.log(parsePrice("100")); // 100
The Trap of Leading Characters and Whitespace
Now, here is where it gets tricky. parseFloat and parseInt are surprisingly forgiving with trailing characters (like "USD" or "px"), but they are absolutely ruthless with leading characters. If the string starts with anything other than a sign (+ or -) or a digit, you get NaN.
If our user types "$49.99" instead of "49.99 USD", our current function fails. Let's look at what happens:
console.log(parsePrice("$49.99")); // NaN
To fix this, I usually strip out common currency symbols or use trim() to handle accidental whitespace. While parseFloat ignores leading whitespace automatically, it's a good habit to be explicit about what you're cleaning. I'll use a simple replace to handle that leading dollar sign.
function parsePrice(input) {
const cleaned = input.trim().replace('$', '');
return parseFloat(cleaned);
}
console.log(parsePrice(" $49.99 ")); // 49.99
Handling the "Not a Number" Void
The final edge case that bites engineers is the empty string or a string containing only whitespace. You might expect parseFloat("") to return 0, but it actually returns NaN. In a shopping cart, NaN is a nightmare because any math you do with it (like adding tax) will just result in more NaNs.
I always wrap these calls in a check or provide a fallback value using the logical OR operator or isNaN(). Here is the "production-ready" version of my logic:
function parsePrice(input) {
if (!input) return 0; // Handle null, undefined, or empty strings immediately
const cleaned = input.trim().replace('$', '');
const result = parseFloat(cleaned);
// If the result is NaN (e.g., the user typed "abc"), return 0
return isNaN(result) ? 0 : result;
}
console.log(parsePrice(" $49.99 ")); // 49.99
console.log(parsePrice("Price: 50")); // NaN (because it starts with 'P')
console.log(parsePrice("")); // 0
One last tip: if you ever use parseInt for things other than decimals, always provide the second argument—the radix. parseInt("10", 10) tells JS explicitly that you're using base-10. It prevents the engine from guessing if you're using octal or hexadecimal, which can lead to some truly bizarre bugs in older environments.
📋 Practical Task
The Messy Weight Converter
You are building a health app that allows users to enter their weight. However, users are inconsistent; some enter "180lbs", some enter " 75.5 kg ", and some just enter "Unknown".
Create a function called cleanWeight that takes a string input and returns a clean number. Your function must:
- Remove any leading or trailing whitespace.
- Correctly parse decimals (e.g., "75.5 kg" should become
75.5). - Handle inputs that start with non-numeric characters (like "Weight: 180") by returning
0. - Handle completely invalid inputs (like "Unknown" or an empty string) by returning
0instead ofNaN.
Test your function with these cases: " 150lbs ", "82.4 kg", "Unknown", and "".
There are no comments for now.