Skip to content

Instantly share code, notes, and snippets.

@camilleriluke
Last active July 5, 2019 09:35
Show Gist options
  • Save camilleriluke/6e9222b7de2be6d7b9a0c5e06610ebef to your computer and use it in GitHub Desktop.
Save camilleriluke/6e9222b7de2be6d7b9a0c5e06610ebef to your computer and use it in GitHub Desktop.
Answering this question
['0', '1','2','2','1','0'].map(parseInt)

A: 0, 1, 2, 2, 1, 0
B: 0, 0, 0, 0, 0, 0
C: 0, NaN, NaN, 2, 1, 0
D: 0, NaN, NaN, NaN, NaN, NaN
E: NaN, NaN, NaN, NaN, NaN, NaN

parseInt (string , radix) https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2

The second argument is the radix which is the base of the number that is being parsed. https://en.wikipedia.org/wiki/Radix

Array.prototype.map ( callbackfn [ , thisArg ] ) https://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19

callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.

Now given that we are passing the parseInt function as a callback to the map we are essentially calling parseInt like this:

parseInt(/* the value of the element */, /* the index of the element */)
parseInt('0', 0) // '0' converted to base 0
parseInt('1', 1) // '1' converted to base 1
parseInt('2', 2) // '2' converted to base 2
parseInt('2', 3) // '2' converted to base 3
parseInt('1', 4) // '1' converted to base 4
parseInt('0', 5) // '0' converted to base 5
0 base 0 = 0
1 base 1 = NaN // because if radix is < 2 or R > 36 it will return NaN
2 base 2 = NaN // 2 is not a valid number in base 2, only 1 or 0 are allowed
2 base 3 = 2
1 base 4 = 1
0 base 5 = 0

So the answer is C.

anyway this is the official answer https://medium.com/dailyjs/parseint-mystery-7c4368ef7b21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment