I was practicing some JavaScript when one of my friends came across this JavaScript code:
document.write(('b' + 'a' + + 'a' + 'a').toLowerCase());
The above code answers "banana"!
Can anyone explain why?
+'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');
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');
'b' + 'a' + + 'a' + 'a'
...is evaluated as....
'b' + 'a' + (+'a') + 'a'
(see: operator precedence)
(+'a') attempts to convert 'a' to a number using the unary plus operator. Because 'a' is not a number, the result is NaN ("Not a Number"):
'b' + 'a' + NaN + 'a'
Although NaN stands for "Not a Number", it's still a numeric type; when added to strings, it concatenates just as any other number would:
'b' + 'a' + NaN + 'a' => 'baNaNa'
Finally, it's lowercased:
'baNaNa'.toLowerCase() => 'banana'
('b' + 'a' + + 'a' + 'a').toLowerCase()
For clarity, let's break this down into two steps. First, we get the value of the parenthesized expression and then we apply the toLowerCase() function on the result.
'b' + 'a' + + 'a' + 'a'
Going L-R, we have:
'b' + 'a' returns ba, this is regular concatenation.ba + + 'a' attempts to concatenate ba with + 'a'. However, since the unary operator + attempts to convert its operand into a number, the value NaN is returned, which is then converted into a string when concatenated with the original ba - thus resulting in baNaN.baNaN + 'a' returns baNaNa. Again, this is regular concatenation.
At this stage, the result from step one is baNaNa.
Applying .toLowerCase() on the value returned from step one gives:
banana
There are many similar puns in JavaScript that you can check out.