Convert boolean result into number/integer

Convert boolean result into number/integer

I have a variable that stores false or true, but I need 0 or 1 instead, respectively. How can I do this?

Solutions/Answers:

Solution 1:

Javascript has a ternary operator you could use:

var i = result ? 1 : 0;

Solution 2:

Use the unary + operator, which converts its operand into a number.

+ true; // 1
+ false; // 0

Note, of course, that you should still sanitise the data on the server side, because a user can send any data to your sever, no matter what the client-side code says.

Solution 3:

Imho the best solution is:

fooBar | 0

This is used in asm.js to force integer type.

Solution 4:

I prefer to use the Number function. It takes an object and converts it to a number.
Example:

var myFalseBool = false;
var myTrueBool = true;

var myFalseInt = Number(myFalseBool);
console.log(myFalseInt == 0);

var myTrueInt = Number(myTrueBool);
console.log(myTrueInt == 1);

Or run it in jsFiddle.

Solution 5:

I created a JSperf comparison of all suggested answers.

TL;DR – the best option for all current browsers is:

val | 0;

.

Update:

Related:  are there dictionaries in javascript like python?

It seems like these days they are all pretty identical, except that the Number() function is the slowest, while the best being val === true ? 1 : 0;.

Solution 6:

The typed way to do this would be:

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