DEV Community

Discussion on: Remembering that "functions are objects" can help in writing more concise code

Collapse
 
jburgy profile image
jburgy •

You do have to be careful with things like

['0', '1', '2'].map(parseInt)
Collapse
 
somedood profile image
Basti Ortiz •

Oh, wow. This is indeed weird. I didn't know this was an outlier.

Why does this happen? Are there any other outliers I should be aware of so I could update the article to mention them?

Collapse
 
ironydelerium profile image
ironydelerium •

That one is a side effect of how the combination of Array.prototype.map and parseInt work - the former calls it's argument with (value, index, array) repeatedly, parseInt expects (value, base) where 2 <= base <= 36, or it returns NaN (ecma-262 1e, 15.1.2.2 "parseInt(string, radix)").

Most of the array iteration methods (forEach, map, every, some) pass 3 arguments; I believe reduce passes 4.

Thread Thread
 
somedood profile image
Basti Ortiz •

Oh, I see now. There is a conflict between the two parameters (index and base). Since the code you mentioned returns [0, NaN, NaN], why does it return 0 in the "zeroth" element of the array? What even is a base 0 number to JavaScript?

As I experimented on passing in 0 as an argument for the base parameter of parseInt, I found that it works normally. Why would that work? Is it just all in the spec?

Thread Thread
 
robertcoopercode profile image
Robert Cooper •

From MDN (radix being the same as base with the previously used verbage):

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
Thread Thread
 
somedood profile image
Basti Ortiz •

Thanks for looking into this! We appreciate your efforts. I'll go make a quick edit to the article now to raise this point.

Collapse
 
robertcoopercode profile image
Robert Cooper •

Ah, thanks for this example! It was fun digging into this.