I have a variable that stores false or true, but I need 0 or 1 instead, respectively. How can I do this?
I was just dealing with this issue in some code I was writing. My solution was to use a bitwise and.
var j = bool & 1;
A quicker way to deal with a constant problem would be to create a function. It's more readable by other people, better for understanding at the maintenance stage, and gets rid of the potential for writing something wrong.
function toInt( val ) {
return val & 1;
}
var j = toInt(bool);
Edit - September 10th, 2014
No conversion using a ternary operator with the identical to operator is faster in Chrome for some reason. Makes no sense as to why it's faster, but I suppose it's some sort of low level optimization that makes sense somewhere along the way.
var j = boolValue === true ? 1 : 0;
Test for yourself: http://jsperf.com/boolean-int-conversion/2
In FireFox and Internet Explorer, using the version I posted is faster generally.
Edit - July 14th, 2017
Okay, I'm not going to tell you which one you should or shouldn't use. Every freaking browser has been going up and down in how fast they can do the operation with each method. Chrome at one point actually had the bitwise & version doing better than the others, but then it suddenly was much worse. I don't know what they're doing, so I'm just going to leave it at who cares. There's rarely any reason to care about how fast an operation like this is done. Even on mobile it's a nothing operation.
Also, here's a newer method for adding a 'toInt' prototype that cannot be overwritten.
Object.defineProperty(Boolean.prototype, "toInt", { value: function()
{
return this & 1;
}});