Explain Codes LogoExplain Codes Logo

Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?

javascript
type-coercion
operator-precedence
unary-plus
Anton ShumikhinbyAnton Shumikhin·Mar 13, 2025
TLDR

The unexpected outcome of ('b'+'a'+ + 'a' + 'a').toLowerCase() hinges on + + 'a', which treats +'a' as a unary plus, coercing 'a' into a number. This fails, yielding NaN. Consequently, the string 'b' + 'a' + NaN + 'a' is created. Transformed to 'baNaNa' and finally, .toLowerCase() turns it into 'banana'.

let magicBanana = ('b'+'a'+ + 'a' + 'a').toLowerCase(); // 'banana' console.log(`Magic banana? ${magicBanana}`); // Console.log: Magic banana? banana. You know, ordinary JavaScript day.

Diving into the unary plus and coercion

The first + plays the role of a concatenation operator. The second + (preceded by a space) acts as a unary plus operator which attempts to coerce the 'a' string into a number. Since 'a' doesn't resemble a number, it spits out NaN.

let aNumber = +'a'; // NaN let addNaN = 'a' + aNumber; // "aNaN" console.log(`Was looking for a number, found ${aNumber} instead`); // Something tells me 'a' is not a number...

What's happening?

  • Space between + operators is paramount, seperating the unary plus from the concatenation plus.
  • Unary plus (+) takes precedence over concatenation.
  • Risk of introducing NaN when unary plus is used on non-numeric strings due to type coercion.

Operator precedence and JavaScript's talent show

JavaScript evaluates expressions from left to right, adhering to operator precedence rules. With various oeprand types (strings and numbers), JS showcases its type juggling skills to understand how to apply these operators.

Cases in point:

  • String + String: Leads to string concatenation ('1' + '1' becomes '11').
  • Number + Number: Performs simple addition (1 + 1 results in 2).
  • String + Number (or vice versa): Triggers type coercion ( thus '1' + 1 gives '11').

Watch out for:

  • +'a', a ToNumber conversion error, ends up as NaN.
  • Unintentional string concatenation due to string coercion when you expected arithmetic addition ('5' + 5 results in '55').

Ensuring smooth sailings with optimization and good practices

Understanding and mindful application of type conversion is vital. Being aware of scenarios where type juggling can occur could save you from unanticipated results in your code.

let unexpected = '5' + 5; // "55" console.log(`Expected 10, got ${unexpected}? JavaScript may have tricked you`); // JS Magic or Trick?

Handy tips:

  • Avoid implicit type conversion, be explicit with your intended types.
  • When in doubt, use explicit conversion methods like Number() or String().

Good practices to adopt:

  • Avoid unclear uses of + operator.
  • For string formation, consider template literals:
`b${'a'}NaN${'a'}`.toLowerCase(); // "banana" console.log(`No more magic tricks!`); // Honest work.
  • Ensure operand types align with your anticipated operation.