I have a variable that stores false
or true
, but I need 0
or 1
instead, respectively. How can I do this?
Imho the best solution is:
fooBar | 0
This is used in asm.js to force integer type.
let integerVariable = booleanVariable * 1;
Javascript has a ternary operator you could use:
var i = result ? 1 : 0;
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);
You can test it in a jsFiddle.
I just came across this shortcut today.
~~(true)
~~(false)
People much smarter than I can explain:
http://james.padolsey.com/javascript/double-bitwise-not/
When JavaScript is expecting a number value but receives a boolean instead it converts that boolean into a number: true and false convert into 1 and 0 respectively. So you can take advantage of this;
var t = true;
var f = false;
console.log(t*1); // t*1 === 1
console.log(f*1); // f*1 === 0
console.log(+t); // 0+t === 1 or shortened to +t === 1
console.log(+f); //0+f === 0 or shortened to +f === 0
Further reading Type Conversions Chapter 3.8 of The Definitive Guide to Javascript.