Posted  24 Feb 2009 - 11:58:45

Category: JavaScript

Convert a boolean to integer in javascript

You have a boolean and wish to convert this to an interger value in JavaScript.


function convertBoolToInt()
var testBool = true;
result = (testBool)?1:0;

Marked as helpful by 73 users


10/15/2013 4:54:41 PM  Ben  wrote:

this is useful if you want custom values for true/false and not 1 and 0. also I don't trust that all javascript interpreters will do implicitly cast the same way. I prefer explicit casting in general

5/22/2013 5:46:39 PM  Warren Gaebel, B.A., B.C.S.  wrote:

Why so complicated? Just use the boolean where the context requires an integer. It converts automatically. Example: (true+true+true+false+true)/ (true-false+true) evaluates to 2. A boolean true behaves like the integer 1 and a boolean false behaves like the integer 0, AND VICE VERSA. There is no need for an explicit conversion.

8/31/2011 2:44:37 PM  wrote:

Do not create unnecessary function, use an explicit expression!

10/21/2009 5:43:36 PM  karaca  wrote:

var x = +false; //prints 0 var x = +true; //prints 1

8/3/2009 5:38:54 PM  didine  wrote:

right simply

© SolutionCottage 2008-2011 9/24/2017 1:05:55 PM