Saturday, June 29, 2019

strange JavaScript .map() "magic"

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

['1', '7', '11'].map(parseInt)
would expect [1, 7, 11]
but it returns [1, NaN, 3]

another "strange" result:

[1, 2, 3, 4, 5].map(console.log);



explanation:
[1, 2, 3, 4, 5].map(console.log);// The above is equivalent to[1, 2, 3, 4, 5].map(
    (val, index, array) => console.log(val, index, array)
);// and not equivalent to[1, 2, 3, 4, 5].map(
    val => console.log(val)
);

ParseInt takes two arguments: string and radix (base, default is 10)

parseInt('1', 0, ['1', '7', '11']); => 1
parseInt('7', 1, ['1', '7', '11']); => NaN
parseInt('11', 2, ['1', '7', '11']); => 3


The Weird History of JavaScript - YouTube

No comments: