JavaScript is Extraordinarily Weird! Hear Me Out! 👨‍💻📢🔥

Arjun Vijay Prakash - Aug 17 '23 - - Dev Community

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!

Image

Answer in 5.

4.

3.

2.

1.

and...

The answer is "banana"

JAVASCRIPT IS JUST CRAZY 🤐🔥

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!

Working

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .