0

I'm there in JavaScript for a long time & it still gives me new things to learn.

According to me, the following line should print the same array back, perhaps it doesn't -

console.log([2, 2, 2, 2, 2, 2].map(parseInt));
// output => [2, NaN, NaN, 2, 2, 2]

console.log([2, 2, 2, 2, 2, 2].map((num) => parseInt(num)));
// output => [2, 2, 2, 2, 2, 2]

Could anyone please help me understand this?

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56

1 Answers1

1

yes so what are the arguments to callback of map

value,index,array

your code sample is executed like this:

console.log(
  [2, 2, 2, 2, 2, 2].map((value, index) => {
    return parseInt(value, index);
  })
);

so you are passing second argument to parseInt , which is index

2nd argument to parseInt is base in which you want to parse the integer

for base 1 and 2 there is no digit 2 .. so it gives NaN

read more about 2nd parameter of parseInt on MDN

Fix is providing only one argument since your numbers are in base 10

console.log(
  [2, 2, 2, 2, 2, 2].map(value => parseInt(value))
);
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
ashish singh
  • 6,526
  • 2
  • 15
  • 35