22
console.log(true+true); //2
console.log(typeof(true+true)); //number
console.log(isNaN(true+true)); //false

Why is adding together 2 boolean types yielding a number? I kind of understand that if they didn't equal (1/0 (binary?)) it would be awkward to try to perform arithmetic on a boolean type, but I can't find the reasoning behind this logic.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118

3 Answers3

17

It works like that because that's how it's specified to work.

EcmaScript standard specifies that unless either of the arguments is a string, the + operator is assumed to mean numeric addition and not string concatenation. Conversion to numeric values is explicitly mentioned:

Return the result of applying the addition operation to ToNumber( lprim) and ToNumber(rprim).

(where lprim and rprim are the primitive forms of the left-hand and the right-hand argument, respectively)

EcmaScript also specifies the To Number conversion for booleans clearly:

The result is 1 if the argument is true. The result is +0 if the argument is false.

Hence, true + true effectively means 1 + 1, or 2.

kviiri
  • 3,282
  • 1
  • 21
  • 30
0

Javascript is a dynamically typed language, because you don't have to specify what type something is when you start, like bool x or int i. When it sees an operation that can't really be done, it will convert the operands to whatever they need to be so that they can have that operation done on them. This is known as type coercion. You can't add booleans, so Javascript will cast the booleans to something that it can add, something like a string or a number. In this case, it makes sense to cast it to a number since 1 is often used to represent true and 0 for false. So Javascript will cast the true's to 1s, and add them together

scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
0

Javascript is loosely typed, and it automatically converts things into other things to fit the situation. That's why you can do var x without defining it as an int or bool

http://msdn.microsoft.com/en-us/library/6974wx4d(v=vs.94).aspx