I have a variable that stores false
or true
, but I need 0
or 1
instead, respectively. How can I do this?
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.