Think of the
filter functions that make it possible to easily loop over arrays.
And don’t forget that Functional Programming is possible with JS as well (1).
But although JS has changed a lot for the better, there is still enough functionality that makes you wonder what is happening under the hood.
Try to guess what the following code will output:
( "b" + "a" + + "a" + "a" ).toLowerCase()
Okay, that was not that hard. The title spoils everything. But now try to explain why this happens.
That’s a bit harder.
But not too hard, right?
It has to do with the
+ + "a".
If we write that a little different we get
a to a number.
+"1" will output the integer
However, JS does not know how to convert
a to a number.
NaN, which has type
For most numbers, it makes sense that we can add them to a string without having to explicitly convert it to a string first.
This is not the case for
Thus allowing us to concat
NaN to string by implicitly converting it to the string
The complete result of all the additions is therefore
Imagine that you have this array of strings
[ "0", "1", "111" ].
You want to convert all the items in this array to an integer.
Seems reasonable easy right?
It is easy to do this using the
Array.map() syntax (look here for more information).
This results in the following code:
[ "0", "1", "111" ].map( parseInt )
However, the code does not do what you expect it to do. This code will output
[ 0, NaN, 7 ]. So why is that?
It turns out that
parseInt wants to receive two parameters(3): a string to parse and a radix to parse the number in.
When we look at the documentation of
Array.map() we can find out that it actually provides three parameters to the function.
The third one is simply ignored.
The parameters are: the element of the array, it’s index and the complete array.
Below is a table trace of the execution of this program.
parseInt function, a radix of
0 is the same as radix
10 so that is simply converting the string to our number system.
A radix of
1 makes no sense, so that is why the output of the function is
NaN in that case.
And as most of you know,
111 is the binary representation of
"111" with radix
This explains the “weird” output that the program gives and if you think about it: it is not weird at all. It is just not something that you would expect.
A possible solution for this “problem” would be to make explicit how many parameters you want to use. This is demonstrated in the code below.
[ "0", "1", "111" ].map( numberString => parseInt( numberString, 10 ) )