Understanding parseInt in JavaScript with Examples

Master parseInt in JavaScript! Learn how it works, its pitfalls, and best practices with code examples.

Understanding parseInt in JavaScript with Examples
JavaScript provides the parseInt
function to convert strings into integers. However, it has some nuances that developers must understand to use it effectively.
Syntax of parseInt
parseInt(string, radix);
string
: The value to be converted.radix
: The base of the numerical system (optional but highly recommended).
Example 1: Basic Usage
console.log(parseInt("42")); // Output: 42
console.log(parseInt("0037")); // Output: 37
Example 2: Using Radix
console.log(parseInt("10", 2)); // Output: 2 (Binary to Decimal)
console.log(parseInt("A", 16)); // Output: 10 (Hexadecimal to Decimal
Why Specifying Radix is Important
If the radix is not specified, JavaScript may misinterpret the number:
console.log(parseInt("08")); // Output: 8 (Modern JS assumes decimal)
console.log(parseInt("08", 10)); // Output: 8 (Explicitly decimal)
Handling Non-Numeric Values
parseInt
stops parsing at the first non-numeric character:
console.log(parseInt("123abc")); // Output: 123
console.log(parseInt("abc123")); // Output: NaN (Not a Number)
Common Mistakes
Not specifying the radix
Assuming
parseInt
rounds numbers
console.log(parseInt("10.9")); // Output: 10 (It truncates, not rounds)
Conclusion
parseInt
is a useful function in JavaScript but requires careful handling, especially with radix. Always specify the radix to avoid unexpected results!
For more JavaScript tips, visit Codercrafter Blogs. 🚀