Bitsy Explains
Home/Cursed JavaScript/Lesson 5

"b" + "a" + +"a" + "a" Spells baNaNa

How "b" + "a" + +"a" + "a" spells baNaNa, what a plus sign in front of a value does, and when that trick is actually useful.

Lesson 5 of 103 min readVideo
Video thumbnail: "b" + "a" + +"a" + "a" Spells baNaNa Watch the 90-second video
Explain like I'm five

A plus sign in front of something is a tiny number maker. It tries to turn whatever comes after it into a number. The letter a is not a number, so the number maker hands back NaN, and the word banana ends up with NaN baked into the middle.

The curse

console.log("b" + "a" + +"a" + "a"); // prints: baNaNa

Look closely at the two plus signs in the middle, with a space between them. The second one is not adding anything.

Step by step

A plus sign with nothing on its left is the unary plus. It works on one value only, and it runs before the normal pluses around it.

  • +"a" tries to turn "a" into a number. The text is not a number, so the result is NaN.
  • "b" + "a" glues two strings into "ba".
  • "ba" + NaN has a string on one side, so NaN is turned into the text "NaN" and glued on. That gives "baNaN".
  • "baNaN" + "a" gives "baNaNa".
console.log(+"a"); // prints: NaN
console.log("ba" + NaN); // prints: baNaN

The space between the two pluses matters. Without it, ++ is the increment operator, and JavaScript refuses to run the line with a syntax error.

The useful part

That plus trick does the same job as Number(), just shorter.

console.log(+"42"); // prints: 42
console.log(+"hello"); // prints: NaN
console.log(+""); // prints: 0
console.log(+true); // prints: 1

It works on text that looks like a number, including decimals like "3.5" and spaces around the digits. Anything else gives NaN. Two results catch people out. An empty string becomes 0, and true becomes 1.

Compare it with parseInt, which reads digits from the start of the text and stops at the first one that doesn't fit.

console.log(+"12px"); // prints: NaN
console.log(parseInt("12px", 10)); // prints: 12

Use + or Number() when the whole text should be a number, and parseInt when you want to pull a number off the front of text like "12px". In shared code many people prefer Number(x), because a lone plus sign is easy to miss when reading.

Bonus twist: really spelling banana

console.log(("b" + "a" + +"a" + "a").toLowerCase()); // prints: banana

toLowerCase turns the capital N's into small ones, and the haunted word becomes a plain banana. It is a fun way to confuse your friends, and a good test of whether you can read each step on your own.

Rule of thumb

A plus sign in front tries to turn something into a number, and text that isn't a number becomes NaN.

Common mistake

Using + to convert form input and forgetting that an empty field becomes 0, not NaN. If an empty value should count as missing, check for "" before you convert.

Check yourself

What does +"42" give?