Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert True->1 and False->0 in Javascript?

Tags:

javascript

Besides :

true ? 1 : 0

is there any short trick which can "translate" True->1 and False->0 in Javascript ?

I've searched but couldn't find any alternative

What do you mean by "short trick" ?

answer : same as ~~6.6 is a trick forMath.floor

like image 506
Royi Namir Avatar asked Feb 09 '13 11:02

Royi Namir


People also ask

Why is 1 true and 0 false JavaScript?

0 and 1 are type 'number' but in a Boolean expression, 0 casts to false and 1 casts to true . Since a Boolean expression can only ever yield a Boolean, any expression that is not expressly true or false is evaluated in terms of truthy and falsy. Zero is the only number that evaluates to falsy.

Is 0 true or false in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

How do you convert false to zero?

int() turns the boolean into 1 or 0 . Note that any value not equal to 'true' will result in 0 being returned.

Is true equal to 1 in JavaScript?

Boolean type take only two literal values: true and false. These are distinct from numeric values, so true is not equal to 1, and false is not equal to 0. I know, that every type in JavaScript has a Boolean equivalent.


2 Answers

Lots of ways to do this

// implicit cast +true; // 1 +false; // 0 // bit shift by zero true >>> 0; // 1, right zerofill false >>> 0; // 0 true << 0; // 1, left false << 0; // 0 // double bitwise NOT ~~true; // 1 ~~false; // 0 // bitwise OR ZERO true | 0; // 1 false | 0; // 0 // bitwise AND ONE true & 1; // 1 false & 1; // 0 // bitwise XOR ZERO, you can negate with XOR ONE true ^ 0; // 1 false ^ 0; // 0 // even PLUS ZERO true + 0; // 1 false + 0; // 0 // and MULTIPLICATION by ONE true * 1; // 1 false * 1; // 0 

You can also use division by 1, true / 1; // 1, but I'd advise avoiding division where possible.

Furthermore, many of the non-unary operators have an assignment version so if you have a variable you want converted, you can do it very quickly.

You can see a comparison of the different methods with this jsperf.

like image 194
Paul S. Avatar answered Sep 20 '22 11:09

Paul S.


Another way could be using Number()

Number(true) // = 1 Number(false) // = 0 
like image 34
Muhammad Avatar answered Sep 22 '22 11:09

Muhammad