Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Adding Booleans

Tags:

javascript

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.

like image 798
Sterling Archer Avatar asked Dec 12 '13 22:12

Sterling Archer


People also ask

Can you add booleans in JavaScript?

Because you can't add booleans, so it converts them to numbers first.

How do you add a boolean attribute?

To add a Boolean attribute: node. setAttribute(attributeName, ''); // example: document. body.

How do you append boolean to form data?

append accepts only a USVString or a Blob . S you will have to convert your data to string and then parse it later on the backend. You can use JSON. stringify to convert your form object to a string.

How do booleans work in JavaScript?

JavaScript provides the Boolean() function that converts other types to a boolean type. The value specified as the first parameter will be converted to a boolean value. The Boolean() will return true for any non-empty, non-zero, object, or array.


1 Answers

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.

like image 174
kviiri Avatar answered Oct 19 '22 00:10

kviiri