Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?

HV Sharma picture HV Sharma · Aug 12, 2019 · Viewed 81.2k times · Source

I was practicing some JavaScript when one of my friends came across this JavaScript code:

The above code answers "banana"! Can anyone explain why?

Answer

SOFe picture SOFe · Aug 12, 2019

+'a' resolves to NaN ("Not a Number") because it coerces a string to a number, while the character a cannot be parsed as a number.

document.write(+'a');
To lowercase it becomes banana.

Adding NaN to "ba" turns NaN into the string "NaN" due to type conversion, gives baNaN. And then there is an a behind, giving baNaNa.

The space between + + is to make the first one string concatenation and the second one a unary plus (i.e. "positive") operator. You have the same result if you use 'ba'+(+'a')+'a', resolved as 'ba'+NaN+'a', which is equivalent to 'ba'+'NaN'+'a' due to type juggling.

document.write('ba'+(+'a')+'a');