[ProgClub programming] Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in Javascript

John Elliot V | ProgClub jj5 at progclub.org
Mon Jun 24 21:42:07 AEST 2019


I didn't believe it. So I wrote this program:

 jj5 at tact:~/desktop/experiment$ cat test.js
 var result = [ '1', '7', '11' ].map( parseInt );
 console.log( result );

And then ran it:

 jj5 at tact:~/desktop/experiment$ nodejs test.js
 [ 1, NaN, 3 ]

Holy cow!

See if you can figure it out yourself. The answers are here [1].

Hint: this is my fix:

 jj5 at tact:~/desktop/experiment$ cat test.js
 var result = [ '1', '7', '11' ].map( s => parseInt( s ) );
 console.log( result );

 jj5 at tact:~/desktop/experiment$ nodejs test.js
 [ 1, 7, 11 ]

May the Force be with you,
John Elliot V

[1]
https://www.reddit.com/r/programming/comments/c4lcls/why_1_7_11mapparseint_returns_1_nan_3_in/

-- 
|_|O|_| ProgClub
|_|_|O| Because every programmer needs a good club!
|O|O|O| https://www.progclub.org/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: jj5.vcf
Type: text/x-vcard
Size: 231 bytes
Desc: not available
URL: <http://www.progclub.org/pipermail/programming/attachments/20190624/456dc81a/attachment.vcf>


More information about the programming mailing list