javascripttype-conversion

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


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?


Solution

  • +'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 nan.

    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');