Sunday, 12 May 2019

Map and parseInt

It was quite a long time that I didn't stumble upon with some JavaScript unexpected behaviour. Well, indeed this is not one issue with the language itself, but a the combination of 2 unfrequently used parameters in 2 frequently used functions.

I was using Array.prototype.map and parseInt and was getting some crazy outputs:

let items = [1.2, 0.3, 2.4, 3.7];
console.log(items.map(parseInt).join(" - "));
//1 - NaN - NaN - NaN

Even more crazy, when using an arrow function invoking parseInt it was working as expected:

console.log(items.map(it => parseInt(it)).join(" - "));
//1 - 0 - 2 - 3

So what? Well, a first google search brought up this explanation. Just read it, but summing up, I was missing that parseInt receives a second parameter, radix, (that we rarely need) and was missing that map (same as filter, foreach...) passes over a second parameter (index) that in many cases we don't need. Both of them combined we get this unexpected behaviour.

One can come up with more examples where we could get similar unexpected behaviours, for example with a format function recieving an optional second parameter:

const format = (st, wrapSt) => (wrapSt || "") +  st.toUpperCase() + (wrapSt || "");
console.log(format("bonjour"));
//bonjour
console.log(format("bonjour", "|"));
//|bonjour|

items = ["bonjour", "ca va", "hey"];
console.log(items.map(format).join(" - "));
//BONJOUR - 1CA VA1 - 2HEY2

No comments:

Post a Comment