JavaScript Map | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

JavaScript Map

Why does this code returns. (1, NaN, 3) let x = ["1", "7", "11"].map(parseInt) console.log(x)

14th Sep 2019, 7:01 PM
Qudusayo
Qudusayo - avatar
3 Answers
+ 2
parseInt takes 2 arguments and the array.map callback takes 3, (value, index, array). parseInt's second argument is the base it should parse, and if it is 0, it finds the base (eg. 0x... is base 16, and a normal number is base 10). Knowing this, this is how it would execute: parseInt(value, index) parseInt("1", 0) -> 1 (parsed as decimal since it isn't prefixed with something to show a different base) parseInt("7", 1) -> NaN (base 1 always seems to return NaN since it's not a valid base) parseInt("11", 2) -> 3 (11 from binary to decimal)
15th Sep 2019, 2:53 PM
JS Coder
+ 1
probably sth with binary. since 1b = 1d 11b = 3d 7 is not binary and cannot be converted so it becomes NaN
14th Sep 2019, 7:11 PM
Anton Böhler
Anton Böhler - avatar
+ 1
Actually parseInt can take one argument. Radix parameter is optional. The thing is you missed calback in map method, so add lambda function: ["1","7","11"].map(o => parseInt(o))
19th Sep 2019, 4:50 PM
Rustem Sharipov
Rustem Sharipov - avatar