1

Today I was trying random letters printing using nodejs, Somehow I tried to print 'banana' in log but unfortunately I miss n (letter) to log but still it works fine. Why does it prints whole banana instead of 'baaa'?

('b' + 'a' + + 'a' + 'a').toLowerCase();

The output is banana but why? Even if + + (empty char) generates NaN then still it should print bananaa not just banana.

Screenshot:

enter image description here

Tahazzot
  • 1,224
  • 6
  • 27
  • it tries to add as a number and gets a NaN and add's the rest as string and also NaN.toString is NaN so it becomes `baNaNa` without toLowerCase. Also doesnt matter when u do `'b' + 'a' + + 'c' + 'a'` this or any other character on the second letter, after + + sign – halilcakar Nov 30 '21 at 07:08
  • If you don't use `toLowercase()` you can see `NaN` in there which tells you that the math operation you're using (`+ + 'a'`) is resulting in something that isn't a number. – Andy Nov 30 '21 at 07:09

3 Answers3

3

The extra + acts as a unary operator on the following 'a', and tries to coerce it to a number, resulting in NaN. The remaining + symbols are all interpreted as string concatenation which causes NaN to be coerced to string ie. ('b' + 'a' + + 'a' + 'a') = ('b' + 'a' + NaN + 'a') = ('baNaNa').

  • You mean it also takes second `a` with `NaN`? Because it has 3 `a` without `NaN` – Tahazzot Nov 30 '21 at 07:12
  • The middle 'a' is coerced to NaN by the preceding `+`, then the rest are concatenated as normal. If you evaluate `+ 'a'` in the dev console, you'll see it evaluates to NaN. – Patrick Stephansen Nov 30 '21 at 07:16
  • 1
    I got it, I just put it for fun & you got infinite amount of upvote :) Have a nice day. Please modify the answer, maybe it will help other people. – Tahazzot Nov 30 '21 at 07:20
1

Interesting !!

console.log(('b' + 'a' + + 'a' + 'a').toLowerCase());

console.log(('b' + 'a' + + 'a' + 'a'));

console.log(( 'a' + + 'b' ));

//output
banana
baNaNa
aNaN

In the 3rd statement, the 'b' is not printed as + + 'b' = NaN //not a number and .toLowerCase() makes it nan hence the word banana

Dharman
  • 30,962
  • 25
  • 85
  • 135
Abhishek Vyas
  • 599
  • 1
  • 9
  • 24
  • 1
    Thanks brother, Now everybody understood the solution :) I already accept an ans. I appreciate your time. – Tahazzot Nov 30 '21 at 07:22
0

Since you are adding nothing with nothing, which is most likely returning NaN

GoldenretriverYT
  • 3,043
  • 1
  • 9
  • 22