Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why does Array.map(Number) convert empty spaces to zeros? JavaScript
When using Array.map(Number) on a string containing spaces, JavaScript converts empty spaces to zeros. This happens due to how the Number() constructor handles string-to-number conversion.
The Problem
Let's examine this behavior with a practical example:
const digify = (str) => {
const parsedStr = [...str].map(Number)
return parsedStr;
}
console.log(digify("778 858 7577"));
[ 7, 7, 8, 0, 8, 5, 8, 0, 7, 5, 7, 7 ]
Notice how the spaces in the string are converted to 0 instead of NaN. This behavior can be problematic when your string legitimately contains zeros.
Why This Happens
The Number() constructor follows JavaScript's type coercion rules. When converting strings to numbers:
console.log(Number(" ")); // 0 - empty/whitespace strings become 0
console.log(Number("")); // 0 - empty string becomes 0
console.log(Number("5")); // 5 - valid number string
console.log(Number("a")); // NaN - invalid characters become NaN
0 0 5 NaN
JavaScript treats empty strings and whitespace-only strings as equivalent to 0 during numeric conversion, following the ECMAScript specification for ToNumber conversion.
Solution: Using parseInt()
To get more predictable behavior, use parseInt() instead:
const parseDigits = (str) => {
const parsedStr = [...str].map(char => parseInt(char, 10));
return parsedStr;
}
console.log(parseDigits("778 858 7577"));
[ 7, 7, 8, NaN, 8, 5, 8, NaN, 7, 5, 7, 7 ]
With parseInt(), spaces correctly return NaN instead of 0, making it easier to distinguish between actual zeros and converted spaces.
Alternative: Filter Out Non-Digits
If you want to remove spaces entirely, filter them out first:
const getDigitsOnly = (str) => {
return [...str].filter(char => !isNaN(char) && char !== ' ').map(Number);
}
console.log(getDigitsOnly("778 858 7577"));
[7, 7, 8, 8, 5, 8, 7, 5, 7, 7]
Comparison of Methods
| Method | Space Result | Use Case |
|---|---|---|
Number() |
0 |
When you want spaces as zeros |
parseInt() |
NaN |
When you want to identify spaces |
| Filter + Number | Removed | When you want digits only |
Conclusion
Use parseInt() instead of Number() when converting character arrays to avoid unexpected space-to-zero conversions. This provides clearer, more predictable behavior in string-to-number transformations.
