How do you convert a string to a number in JavaScript?
Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
In JavaScript, there are several methods to convert a string representation of a number into an actual numeric type, each with distinct edge case behaviors:
### 1. Number(str) Function (Recommended for Exact Numbers)
Parses the entire string as a number. Returns NaN if the string contains any non-numeric characters (except leading/trailing whitespace):
Number("42"); // 42
Number("42.5"); // 42.5
Number("42px"); // NaN (strict parsing)
Number(""); // 0
### 2. Unary Plus Operator (+str)
The fastest syntax, behaves identically to Number(str):
+"123.45"; // 123.45
+"abc"; // NaN
### 3. parseInt(str, radix)
Parses characters from left to right until encountering an invalid character. Always provide radix 10 to prevent legacy octal misinterpretations:
parseInt("42px", 10); // 42
parseInt("010", 10); // 10
parseInt("abc", 10); // NaN
### 4. parseFloat(str)
Parses floating-point decimals from left to right:
parseFloat("3.14159rad"); // 3.14159
### Comparison Summary:
Use Number() or + when validating clean numbers where trailing letters indicate an invalid input; use parseInt() or parseFloat() when parsing CSS values like "16px" or "2.5rem".
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.