BaNaNa
This week, Victor Ribero tweeted this JavaScript craziness.
// Returns "banana"
('b' + 'a' + + 'a' + 'a').toLowerCase();
So… what the hell is going on here?
Not a number
The trick is in the + + 'a'
, specifically, the + 'a'
.
There’s no number between the two plus signs. The browser attempts to add nothing to 'a'
, which returns NaN
(short for Not a Number). Using 'a'
is part of the trick to mask what’s happening. You could use any string here and it would still work.
Because all of the other characters are strings, the browser coerces NaN
into a string and concatenates the rest of the string, resulting in baNaNa
.
The final part of the trick is the lowerCase()
method, which turns the capital N
’s from NaN
into lowercase and hides what’s really happening.
How I figured this out
I was stumped as hell when I first saw this. To be honest, the only reason I figure it out was because of Chrome’s awesome “preview as you type” feature in the Console tab of dev tools.
I was typing this out, and as soon as I got to ('b' + 'a' + + 'a')
, it showed, "baNaN"
.
So, in short: JavaScript is weird, and the people who come up with this stuff are, too.