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

Javascript

Javascript Problem Overview


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 for Math.floor

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Here is a more logical way Number()

Number(true) // = 1
Number(false) // = 0

Solution 3 - Javascript

...or you can use +true and +false

Solution 4 - Javascript

You can use ~~boolean, where boolean is (obviously) a boolean.

~~true  // 1
~~false // 0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoyi NamirView Question on Stackoverflow
Solution 1 - JavascriptPaul S.View Answer on Stackoverflow
Solution 2 - JavascriptMuhammadView Answer on Stackoverflow
Solution 3 - JavascriptbsiamionauView Answer on Stackoverflow
Solution 4 - JavascriptwhirlwinView Answer on Stackoverflow