DEV Community

Cover image for JavaScript is Extraordinarily Weird! Hear Me Out! ๐Ÿ‘จโ€๐Ÿ’ป๐Ÿ“ข๐Ÿ”ฅ
Arjun Vijay Prakash
Arjun Vijay Prakash

Posted on

JavaScript is Extraordinarily Weird! Hear Me Out! ๐Ÿ‘จโ€๐Ÿ’ป๐Ÿ“ข๐Ÿ”ฅ

Last night, I found an interesting JavaScript question, and I bet you won't be able to answer this without cheating.

What do you think is the output of this code snippet?

Let me know in the comments!

("b" + "a" + + "a" + "a").toLowerCase()
Enter fullscreen mode Exit fullscreen mode

The Options are given as following

  • baaa
  • ba01100001a
  • baa
  • ba1a

The question does look simple, but the answer will definitely blow your mind.

Did you get any of these? The interesting thing is - all the options provided above are wrong!


Answer in 5.






The answer is "banana"


Before you get freaked out and ask me "Are you mad?", let me tell you this is the reason why "JavaScript is Extraordinarily Weird". You see its beauty lies within its complexity!


Let's break down the code step by step to understand WHY!:

  • "b" + "a" concatenates the strings resulting in "ba".

  • + + "a" is trying to convert the string "a" to a number and then concatenating it with the above string "ba". Since "a" is not a valid numeric representation, the result of this conversion is NaN ("Not-a-Number").

  • "ba" + NaN concatenates the string "ba" with the value NaN, resulting in the string "baNaN".

  • "baNaN" + "a" concatenates the string "baNaN" with the string "a", resulting in the string "baNaNa".

  • .toLowerCase() is then called on the string "baNaNa". This method converts all characters in the string to lowercase, which further results in the string "banana".

So, the final output of the code is "banana".

Tell me how long it took you to answer this simple question in the comments!

Top comments (2)

jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Step 2 in your working is kind of incorrect, it is the unary plus on it's own that is forcing the attempted coercion to a number - and hence the NaN. The first (normal, binary) plus has no bearing here, and is simply doing string concatenation as one would expect.

It's only 'weird' if your knowledge of JS is incomplete.

arjuncodess profile image
Arjun Vijay Prakash

Actually, I was not wrong, but incomplete.

Thanks for letting me know! I edited the step and made the point correct.