-3

I saw this snippet in a video online (if anyone can find the link, please feel free to add it to the question).

The video was quite short, so there was no explanation as to why JavaScript returns this really random string.

This probably has something to do with how JavaScript handles certain types...

2 Answers2

4

It doesn't:

console.log(new Array(4).join(""+10) + " Batman!")

However, this does:

console.log(new Array(5).join("a"-10) + " Batman!")

Your code didn't work because of two reasons:

  1. Addition with a string and a number gets interpreted as string concatenation, so ""+10 becomes the string "10". You have to use subtraction.
  2. Even so, changing to subtraction isn't enough because the empty string "" converts to the number 0 and results in 0-10 which is the number -10 which finally gets converted to the string "-10" by join(). You have to put something into the quotes that is not a valid number.

The reason it behaves this way, is that JavaScript sees the subtraction and tries to convert the string "a" into a number, but it's not a valid number so it returns NaN (meaning "not a number"). It then tries to subtract 10 from it, which also returns NaN. The result is that you're calling new Array(5).join('NaN'), which joins 5 empty array elements with the string "NaN" => NaNNaNNaNNaN and then concatenating the string " Batman!" to it.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
0

The string isn't random it is an acronym NaN (Not a Number). In order to make the code work the way you ask about you would need to have it evaluate against a non-numeric type.

console.log(new Array(4).join(Number('y tho') + 'a')+' Batman!');
D Lowther
  • 1,609
  • 1
  • 9
  • 16