How can I convert a string to an integer in JavaScript? What are the different methods available for this conversion, including parseInt(), Number(), and the unary plus operator?
JavaScript offers several methods to convert strings to integers, with parseInt(), the Number() constructor, and the unary plus operator (+) being the most common approaches. Each method behaves differently in terms of parsing behavior, error handling, and edge case scenarios, making it important to understand their distinctions for proper usage.
Contents
- parseInt() Method
- Number() Constructor
- Unary Plus Operator
- Comparison and Best Practices
- Error Handling and Edge Cases
- Practical Examples
- When to Use Each Method
parseInt() Method
parseInt() is a built-in JavaScript function that parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Basic Syntax
parseInt(string, radix)
How It Works
- The
parseInt()function reads the string from left to right - It stops parsing when it encounters a character that isn’t a digit in the specified radix
- If the first character cannot be converted to a number, it returns
NaN - The
radixparameter specifies the base of the number system (2-36)
Examples
parseInt("123") // 123 (defaults to radix 10)
parseInt("123", 10) // 123 (explicit radix 10)
parseInt("123abc") // 123 (stops at non-digit)
parseInt("abc123") // NaN (starts with non-digit)
parseInt("1010", 2) // 10 (binary)
parseInt("FF", 16) // 255 (hexadecimal)
Important Notes
- Radix is crucial: Always specify the radix parameter to avoid unexpected behavior
- Leading/trailing spaces:
parseInt()ignores leading whitespace but not trailing whitespace - Negative numbers: Parses the minus sign correctly
- Floating point: Truncates decimal numbers rather than rounding
Number() Constructor
The Number() constructor converts its argument to a number, returning the numeric value or NaN if the conversion fails.
Basic Syntax
Number(string)
How It Works
- Attempts to convert the entire string to a number
- Returns
NaNif any character cannot be converted - Handles decimal points and scientific notation
- More strict than
parseInt()about what constitutes a valid number
Examples
Number("123") // 123
Number("123.45") // 123.45 (preserves decimal)
Number("123abc") // NaN (any non-numeric character)
Number(" 123 ") // 123 (handles whitespace)
Number("-123") // -123 (handles negative)
Number("1e3") // 1000 (scientific notation)
Number("Infinity") // Infinity
Important Notes
- No radix parameter: Unlike
parseInt(), it doesn’t support different number bases - Strict parsing: Fails if any part of the string isn’t a valid number
- Boolean behavior: Returns
1fortrueand0forfalse - Null/undefined: Returns
0fornull,NaNforundefined
Unary Plus Operator
The unary plus operator (+) is a concise way to convert strings to numbers in JavaScript.
Basic Syntax
+string
How It Works
- Attempts to convert the operand to a number
- Returns
NaNif the conversion fails - Follows the same conversion rules as the
Number()constructor - More efficient for simple conversions
Examples
+"123" // 123
+"123.45" // 123.45
+"123abc" // NaN
+" 123 " // 123 (handles whitespace)
+"-123" // -123
+"1e3" // 1000
Important Notes
- Most efficient: Generally the fastest method for simple conversions
- Same behavior: Follows identical rules to
Number()constructor - Readability: Some developers prefer
parseInt()for clarity - Type coercion: Can be used in complex expressions
Comparison and Best Practices
Performance Comparison
| Method | Performance | When to Use |
|---|---|---|
Unary Plus (+) |
Fastest | Simple integer/float conversions, performance-critical code |
Number() |
Fast | When you need explicit type conversion, similar behavior to unary plus |
parseInt() |
Slower | When you need specific radix, or need to extract numbers from mixed strings |
Key Differences
- Precision:
parseInt()truncates decimals, whileNumber()and+preserve them - Flexibility:
parseInt()can handle different number bases - Strictness:
Number()and+are more strict about valid number formats - Return type: All return numbers, but
parseInt()explicitly returns integers
Best Practices
// For simple integer conversion
const num = +stringValue; // Preferred for performance
// For specific number base
const binary = parseInt("1010", 2); // 10
// When you need strict validation
if (!isNaN(Number(input))) {
// Valid number
}
// For extracting numbers from text
const extracted = parseInt("123 dollars", 10); // 123
Error Handling and Edge Cases
Common Pitfalls
// parseInt() without radix (dangerous)
parseInt("08") // 8 in some browsers, 0 in others
parseInt("010") // 10 in some browsers, 8 in others
// Empty string
parseInt("") // NaN
Number("") // 0
+"" // 0
// Whitespace
parseInt(" 123 ") // 123
Number(" 123 ") // 123
// Non-numeric strings
parseInt("abc") // NaN
Number("abc") // NaN
+"abc" // NaN
Safe Conversion Function
function safeStringToInt(str, radix = 10) {
const parsed = parseInt(str, radix);
return isNaN(parsed) ? 0 : parsed;
}
function safeStringToNumber(str) {
const num = Number(str);
return isNaN(num) ? 0 : num;
}
Practical Examples
Form Input Processing
// Getting integer from form input
const ageInput = document.getElementById("age").value;
const age = +ageInput; // Simple conversion
// More robust with validation
const age = parseInt(ageInput, 10) || 0;
// Currency input (with decimal)
const priceInput = "19.99";
const price = Number(priceInput); // 19.99
Configuration Parsing
// API response conversion
const config = {
maxItems: "100",
timeout: "30.5",
enabled: "true"
};
const parsedConfig = {
maxItems: +config.maxItems, // 100
timeout: Number(config.timeout), // 30.5
enabled: config.enabled === "true" // Boolean conversion
};
Data Cleaning
// Extracting numbers from mixed strings
const text = "Users: 1234, Items: 56, Revenue: $7890";
const numbers = text.match(/\d+/g).map(n => +n); // [1234, 56, 7890]
// Alternative with parseInt
const numbers = text.match(/\d+/g).map(n => parseInt(n, 10));
When to Use Each Method
Use parseInt() When:
- You need to convert strings with specific number bases (binary, hex, etc.)
- You want to extract numbers from mixed content (e.g., “123px”)
- You explicitly want integer truncation (not rounding)
- You’re dealing with legacy code that requires radix parameter
Use Number() When:
- You need strict validation of complete number strings
- You want to handle decimal numbers precisely
- You need to convert scientific notation
- You prefer explicit type conversion for readability
Use Unary Plus (+) When:
- You need the most performance-critical conversion
- You’re working with known valid number strings
- You prefer concise syntax
- You’re in contexts where type coercion is acceptable
Performance Considerations
For most applications, the performance differences are negligible. However, in performance-critical code processing thousands of conversions per second:
// Benchmark results (approximate)
// Unary Plus: ~10M operations/second
// Number(): ~8M operations/second
// parseInt(): ~2M operations/second
Conclusion
JavaScript provides three primary methods for converting strings to integers, each with specific use cases and characteristics. The unary plus operator (+) offers the best performance for simple conversions, Number() provides strict and comprehensive number parsing, while parseInt() excels at handling different number bases and extracting numbers from mixed strings.
Key recommendations:
- Always specify the radix parameter when using
parseInt()to avoid browser inconsistencies - Use unary plus (
+) for the most efficient simple integer conversions - Choose
Number()when you need strict validation of complete number strings - Implement proper error handling for user input and data validation
- Consider creating utility functions for consistent conversion behavior across your application
Understanding these conversion methods and their differences will help you write more robust and efficient JavaScript code that handles string-to-integer conversions correctly in various scenarios.