Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does ('b' + 'a' + + 'a' + 'a') return "banana"?

Can you guess the result?

JavaScript
console.log(('b' + 'a' + + 'a' + 'a').toLowerCase());
Show answer and explanation

The answer is "banana".

What actually happens here is the following:

The plus operator is defined for numbers and strings and as soon as a string is present on either the left or right side, a string concatenation is performed.

If we follow the execution path, this is what happens:

// 1st step
'b' + 'a' -> 'ba'
// 2nd step
'ba' + + 'a' // wait a second!

There are two plus operators in this expression. But one of those is actually a prefix-operator, and not a classical plus. What it does is converting the right-side argument to a number, but converting 'a' to a number will actually yield NaN! Let’s continue with following the execution path:

// 1st step
'b' + 'a' -> 'ba'
// 2nd step
'ba' + + 'a' -> 'ba' + NaN -> 'baNaN'
// 3rd step
'baNaN' + 'a' -> 'baNaNa'
// 4th step
'baNaNa'.toLowerCase() -> 'banana'
Take the full quiz Next question →

More Type Coercion questions

  1. Why does 1 + "2" + "2" return "122"?
  2. Why is false == '0' true in JavaScript?
  3. Why is 3 > 2 > 1 false in JavaScript?
  4. What do true == [] and true == ![] return?
  5. Why does [] + {} return "[object Object]"?

Related topics