top | item 34768135

(no title)

contextnavidad | 3 years ago

It passes the value and index to `parseInt`, where the 2nd argument is `base`. So it does not return `[10, 10, 10]` as you'd expect. It returns `[10, NaN, 2]` instead.

You have to do `['10', '10', '10'].map((val) => parseInt(val, 10));` to get the "expected" output. In addition, you should always provide `base` to `parseInt` otherwise it has it's own interpretation infered by the value you give it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

discuss

order

benatkin|3 years ago

or just this:

  ['10', '10', '10'].map(val => parseInt(val))
Leading zeroes can often be considered invalid input, and you may be able to safely assume that it has been dealt with already.

Also the parens around a single argument of an arrow function are a superstitious thing suggested by some well-known react developer a while back, I think.

contextnavidad|3 years ago

I have my linting setup to force a base on `parseInt`, for the extra characters I do feel it's worth it for the safety.

The extra parentheses is just habit from Prettier formatting :)

jakear|3 years ago

Also, no reason to write extra characters just to prevent people from using hexadecimal, it's often convenient and it comes for free!

vbezhenar|3 years ago

My favourite interview question is asking what would return `"192.168.0.1".split(".").map(parseInt)` and why.

JeremyBanks|3 years ago

That seems like a very bad interview question

PoignardAzur|3 years ago

I didn't know about that one. What the hell, JavaScript?