Dimritium

Posted on

# JS Gotchas! (map with parseInt)

In this series we would be discussing on some of the gotchas that I encounter while working with JavaScript. As evident from the title, in this one we would be looking at a problem statement related to `Array.prototype.map` and `parseInt`.

Note: Please do not confuse with `Map` object that holds key value pair, I will refer `Array.prototype.map`as map in this article

### The problem statement:

Let’s try to figure out the output of the following snippet:

``````let date = “2020–12–12”;
let res = date.split(“-”).map(parseInt);
console.log(res);
``````

### The output:

``````[2020, NaN, 1]
``````

Interesting, isn’t it? 2020 was as expected but what happened to other elements of `res` ? Why the other elements failed to parse as integers?

Now lets dive into how JS interpreted the statement.

When we apply `map` operation on an array in JS, it expects a callback function and that callback function we have provided that is `parseInt`. In addition to that `map` always passes 3 arguments to the callback function. These 3 arguments being:

1. The element itself
2. index of the element
3. the whole array

If you want to confirm this you can run the following snippet in the console:

``````[2, 3, 4].map((x, y, z) => console.log(x, y, z))
``````

The output will be:

``````2 0 [2, 3, 4]
3 1 [2, 3, 4]
4 2 [2, 3, 4]
``````

Thus it is clear that this is the way map works.

Now let’s get back to our initial problem statement

The `parseInt` accepts 2 agruments:

1. `string`: the value to parse
2. radix(optional): an integer between 2 and 36 denoting the base in mathematical numeral system

Since map passes the 3 arguments, the first (the element) and second (element’s index) is picked up by the `parseInt` but the third (the array) is neglected.

Thus the radix value is being set as the index of the element. Thus in our initial problem, following iterations are performed for `parseInt`:

``````//first iteration
parseInt("2020", 0);

//second iteration
parseInt("12", 1);

//third iteration:
parseInt("12", 2);
``````

And since we need to have radix as 10 (if working with decimal number system), our expected result is not met.

### The solution (maybe):

``````// modified res
res = date.split(“-”).map((elem) => parseInt(elem));
``````

Note: Be careful with the above solution as `parseInt` implementation is up to the browser and not all browser have default radix set to 10, thus it is always advised to pass radix value whenever using `parseInt`

### Other Solutions:

``````// passing radix value explicitly for the sake of browsers
res = date.split(“-”).map((elem) => parseInt(elem, 10));

// using Number
res = date.split(“-”).map(Number);
``````

This was my first article related to JS, let me know your thoughts in the comment section.

Referenced articles:

Cover Photo by Joan Gamell on unsplash

``````let date = "2020–12–12";