Why does Array.map(Number) convert empty spaces to zeros? JavaScript


Let’s say we are given the following code and output and we need to figure out why JavaScript converts empty strings(“ “) to 0 −

const digify = (str) => {
   const parsedStr = [...str].map(Number)
   return parsedStr;
}
console.log(digify("778 858 7577"))

Output

[
7, 7, 8, 0, 8,
5, 8, 0, 7, 5,
7, 7
]

This behaviour can be very disturbing especially when we have some 0 in the string as well

This actually happens because inside of the map() function when we are converting each character to its numerical equivalent using Number, what it does is it actually uses Abstract Equality Comparison (==) instead of Strict Equality Comparison (===) according to which ' ' == 0 yields true and thus each space is converted to 0.

To prevent this absurd behaviour we can make some tweak in our map() function like this −

Example

const sin = (str) => {
   const parsedStr = [...str].map(i => parseInt(i, 10))
   return parsedStr;
}
console.log(sin("778 858 7577"))

Thus, whenever a space is encountered, it will be converted to NaN and which is a more logical behavior.

Output

[
7, 7, 8, NaN, 8,
5, 8, NaN, 7, 5,
7, 7
]

Updated on: 18-Aug-2020

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements