
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why Does Array Map Convert Empty Spaces to Zeros in 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 ]
Advertisements