-2

I'm struggling to understand why this examples below end up with this kind of results.

String([,,,]); // ',,' why?


Number([8,8]); // NaN    why?

please explain with details if possible

David784
  • 7,031
  • 2
  • 22
  • 29
Shaqe
  • 5
  • 1
  • 1
    Why are you even trying to do this with arrays? – VLAZ Jul 14 '21 at 14:22
  • 1
    Cause numbers separate the decimals with . and not with , that is used to join arrays to a string. – Jonas Wilms Jul 14 '21 at 14:25
  • 1
    In the first case, trailing commas are ignored when creating an array. Hence 2 commas instead of 3. – David784 Jul 14 '21 at 14:25
  • 3
    @pilchard weird, the previous question seems to overlap with this one: [Curious behavior of String()](https://stackoverflow.com/q/68377293). I can only assume there is a course that is giving out these bizarre tasks, it just boggles my mind *why*. – VLAZ Jul 14 '21 at 14:30

1 Answers1

0

Note that String calls the toString method on the object, which, for arrays, is equivalent to calling Array#join.

String([,,,]);

[,,,] is an array with 3 empty elements. [,,,].join() will then put two commas as separators between the empty elements, resulting in ",,".

Number([8,8]);

[8,8].join() returns "8,8", which cannot be parsed as a Number, so it produces NaN.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80