Spelling “Banana” with JavaScript

Cam Dziurgot
System Weakness
Published in
2 min readMar 30, 2023

--

You could read the title of this article and have the answer, or we can dive into the sneaky way to spell out “banana” in the JavaScript console, and why it works.

Photo by Simone Hutsch on Unsplash

The Code

Let’s not jump the shark and get right into the code that spells out banana.

const banana = "b" + "a" + + "a" + "a";
console.info("B: ", banana);

Seems off, right? All the a’s are there, but no n’s.. But if you copy/pasta this code snippet into your console, you’ll get the following output.

Banana output

So let’s take a deeper dive into JavaScript and see why this is happening.

The Reason

Some of you might have caught on that "n"’s alone aren’t being inserted into the string we concatenated, but NaN, Not a Number, is injected into the output somehow. Let’s break down how the banana variable is defined.

The "b" and "a" concatenated like normal strings here, so once we get to the second + operator, the string defined is "ba". Now we have immediately after a second + operator followed by a string, which attempts to convert the string "a" into a number. Since "a" is Not a Number though, we end up with NaN instead. So at that point, the operation turns into "ba" + NaN + "a". Adding NaN to a string converts it into a string, and then the last "a" is added. And that is how JavaScript can create a banana string.

Conclusion

JavaScript is a powerful language that has dominated web development for years. A big reason for this is because of the flexibility in the language. And with that flexibility, we get a lot of fun functionality and hacks like this one.

Good luck, and happy coding!

This article was created with assistance from ChatGPT, a language model developed by OpenAI.

--

--

Full stack web developer interested in designing cloud based software systems.