-3

I would expect something like NaN or undefined but

console.log(true+1)

clearly gives me 2. Why?

Ketus
  • 123
  • 1
  • 11

2 Answers2

3

According to the documentation:

// Boolean + Number -> addition

true + 1 // 2

And:

// Boolean + Boolean -> addition

false + false // 0

So:

console.log(false + 3)//returns 3
console.log(true + 3)//returns 4

And also:

console.log((true+true)*(true+true+true))//returns 6

Here is the link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

Community
  • 1
  • 1
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
2

JavaScript is very willing to convert data types. In your example it converts true to the number 1 so that it can be added to another number.

These conversions can lead to surprising results at times. See the humorous Wat talk for some more surprising results.

flup
  • 26,937
  • 7
  • 52
  • 74