I have a variable that stores false
or true
, but I need 0
or 1
instead, respectively. How can I do this?
-
9Here's a performance comparison of some of the provided techniques: http://jsperf.com/conversion-from-boolean-to-number. – Sam Jan 23 '14 at 04:35
-
6**Node.JS** users will want to use `bool === true ? 1 : 0`, as it is by far the fastest in V8. – Qix - MONICA WAS MISTREATED Mar 17 '14 at 20:27
-
6or just `bool ? 1 : 0;` – Mouloud85 Feb 26 '16 at 10:15
22 Answers
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.

- 233,373
- 50
- 316
- 318
-
65Albeit cool (I had never thought of this), it is [**incredibly** slow](http://jsperf.com/boolean-int-conversion/2) (97% slower in Chrome, to be exact). Be wary! – Qix - MONICA WAS MISTREATED Mar 17 '14 at 04:53
-
@Qix Thank you: that is fascinating. Actually, no, it's astonishing. Though a comparison with the Number constructor would also be interesting... – lonesomeday Mar 17 '14 at 08:59
-
6Check out [this revision](http://jsperf.com/boolean-int-conversion/3). `Number()` is even slower. – Qix - MONICA WAS MISTREATED Mar 17 '14 at 16:11
-
39It appears `bool === true ? 1 : 0` is the fastest, with a close second from `bool | 0`. – Qix - MONICA WAS MISTREATED Mar 17 '14 at 16:12
-
1
-
Strange, faster method here in my chrome... tested with perfomance.now() in this function `function timeit(a, b, c, d) {c = performance.now(); for(d = 0; d < b; d++) a(); return performance.now()-c}`. Pass function and number of loops. – caiohamamura Apr 30 '16 at 01:22
-
1@Qix When you [do the microbenchmarks properly](https://mrale.ph/blog/2012/12/15/microbenchmarks-fairy-tale.html), all of the test cases [have the same performance](https://jsperf.com/boolean-int-conversion/13). – Bergi Jul 21 '19 at 21:13
-
-
With TypeScript linter tslint installed in your IDE, this gives an error `Operator '+' cannot be applied to types 'number' and 'boolean'`. So, you shouldn't do this in JavaScript as well. – Derk Jan Speelman Dec 02 '19 at 10:57
-
@lonesomeday mine surely does, maybe it's my relatively strict tslint config – Derk Jan Speelman Dec 09 '19 at 14:59
-
4@DerkJanSpeelman The fact that something is not allowed in Typescript does not mean that you shouldn't do it in Javascript. They are different (albeit related) languages. – lonesomeday Dec 09 '19 at 17:14
-
The ternary solution is one of the fastest ways. Other solutions like `+true` or `Number(true)` are extremely slow. See [benchmark](https://jsben.ch/dYdis). – Domske Jan 30 '21 at 11:47
-
@lonesomeday this is debatable, TypeScript tries to unify typing standards which JavaScript lacks in the first place by conventionally framing definitions. TypeScript has changed a lot about how I type in Vanilla JavaScript. For instance adding (+) to a boolean doesn't make sense mathematically, hence it's very slow because this is not a logical route JavaScript implementers bothered to optimize. – vdegenne Aug 24 '22 at 10:06
-
@vdegenne Saying "it's good advice" is different to saying "it's correct". Saying Typescript rules produce "correct" JS is nonsense. – lonesomeday Aug 26 '22 at 12:07
-
I think the bigger problem with this is that it's trying to be [clever](https://softwareengineering.stackexchange.com/q/25276/52483), rather than readable & maintainable. – Ian Dunn Dec 29 '22 at 16:48
Javascript has a ternary operator you could use:
var i = result ? 1 : 0;

- 16,770
- 7
- 43
- 49
-
15Best answer. Why? This works on truthiness which is more general and accepts any type (string, number, etcetera.) The unary answer is clever indeed, but if I pass it a string it returns `NaN`. So if you want L33T and guarantee the input, go urary, otherwise methinks the ternary + truthy test is best. – gdibble Jun 13 '17 at 18:31
-
This solution is basically minimizing an `if` statement using the ternary operator. – Mr PizzaGuy Nov 11 '20 at 19:34
-
3The ternary solution is one of the fastest ways. Other solutions like `+true` or `Number(true)` are extremely slow. See [benchmark](https://jsben.ch/dYdis). – Domske Jan 30 '21 at 11:46
-
@Dominik That benchmarking tool is extremely confusing and misleading. https://jsbench.me/ is a much better alternative. – m4heshd Sep 23 '21 at 23:47
Imho the best solution is:
fooBar | 0
This is used in asm.js to force integer type.

- 4,249
- 1
- 32
- 34
-
3
-
3
-
@ESR it casts everything to a number but not always the number you want, if you're dealing with other truthy types. `1 | 0 = 1; 0 | 0 = 0; true | 0 = 1; false | 0 = 0; 'foo' | 0 = 0; undefined | 0 = 0` – Luke Miles Aug 06 '20 at 21:37
-
3Typescript error: `The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.` – Cedric Ipkiss Jan 29 '21 at 15:33
-
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.

- 196,159
- 39
- 305
- 313

- 9,880
- 4
- 43
- 49
-
5This is the best answer by far. At the bottom of course. Only "it takes an object" isn't right. – Rudie Oct 20 '13 at 02:49
-
3Link to mdn is much better than w3schools(eeek !): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number – Olivvv Jan 10 '14 at 17:17
-
4I think this is the best way because it's easy to read and intention-revealing. – Sam Jan 23 '14 at 04:14
-
6
-
Nice, that's exactly what I would do. Instead of using a ternary expression. – kalicki2k Oct 23 '20 at 12:43
-
The ternary solution is one of the fastest ways. Other solutions like `+true` or `Number(true)` are extremely slow. See [benchmark](https://jsben.ch/dYdis). – Domske Jan 30 '21 at 11:49
-
There is a gotcha. If the number is greater than 32 bits, the `| 0` operator will yield a negative value. I personally solved this by using `||` instead of `|` – Ploppz Apr 01 '21 at 14:34
The typed way to do this would be:
Number(true) // 1
Number(false) // 0

- 23,316
- 2
- 31
- 31
-
The ternary solution is one of the fastest ways. Other solutions like `+true` or `Number(true)` are extremely slow. See [benchmark](https://jsben.ch/dYdis). – Domske Jan 30 '21 at 11:49
-
-
-
-
@Devmyselz the question is converting boolean to number. "True" is not boolean. – rooby Aug 03 '23 at 02:10
I created a JSperf comparison of all suggested answers.
TL;DR - the best option for all current browsers is:
val | 0;
.
Update:
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;
.

- 1,004
- 9
- 14
-
2Interestingly, the ternary is now fastest in Chrome 64.0.3282 on macOS 10.13.3. – 2540625 Feb 13 '18 at 23:49
-
1That would be the fastest option, at the time. That is distinct from it being the best option. – mikemaccana Jan 27 '20 at 15:49
I just came across this shortcut today.
~~(true)
~~(false)
People much smarter than I can explain:

- 367
- 3
- 3
-
4Interesting. I learned something new today. I won't use this technique in any project, though, because its potential to confuse future-me or teammates. – nicholaides Mar 08 '12 at 01:57
TL;DR: Avoid Number
constructor and +bool
; use a simple if
by default; resort to bool | 0
, 1 * bool
if benchmarks in your project do better this way.
This is quite an old question, and there exist many valid answers. Something I've noticed is that all benchmarks here are irrelevant - none take into account branch prediction. Also, nowadays, JS engines don't simply interpret the code, they JIT compile it to native machine code and optimize it prior to execution. This means that, besides branch prediction, the compiler can even substitute expressions with their final value.
Now, how do these 2 factors affect the performance of, well, boolean to integer conversion? Let's find out! Before we get into the benchmarks, it is important to know what we benchmark. For the conversion, we're using the following seven conversion methods:
- Number constructor:
Number(bool)
- If statement (ternary used):
bool ? 1 : 0
- Unary operator
+
:+bool
- Bitwise OR:
bool | 0
- Bitwise AND:
bool & 1
- Bitwise double NOT:
~~bool
- Number multiplication:
bool * 1
"Conversion" means converting false
to 0
and true
to 1
1. Each conversion method is ran 100000 times, measuring operations/millisecond. In the following tables, conversion methods will be grouped to their results accordingly. The percentage after the result represents how slow this method is compared to the fastest, in the same browser. If there is no percentage, the method is either the fastest or the difference is negligible (<0.01%). Benchmarks are run on a Macbook Pro 16-inch machine, with the Apple M1 Pro 10-core CPU and 16GB of RAM. Browsers are Chrome 102, Firefox 101 and Safari 15.5.
The first benchmark converts the constant true
:
Method | Chrome (V8) | Firefox (Spidermonkey) | Safari (Webkit) |
---|---|---|---|
Number(bool) |
31745.89 | 392.35 - 91.48% | 31231.79 |
bool ? 1 : 0 |
31592.8 - 0.48% | 4602.64 | 27533.47 - 11.84% |
+bool |
31332.57 - 1.3% | 4463.41 - 3.02% | 27378.7 - 12.34% |
bool | 0 |
31488.5 - 0.81% | 4441.4 - 3.5% | 27222 - 12.84% |
bool & 1 |
31383.17 - 1.14% | 4459.64 - 3.11% | 27317.41 - 12.53% |
~~bool |
31265.85 - 1.51% | 4442.35 - 3.48% | 27434.72 - 12.16% |
bool * 1 |
31374.4 - 1.17% | 4444.05 - 3.45% | 27381.19 - 12.33% |
Interesting! V8 shows some huge numbers, all of them approximately the same! Spidermonkey doesn't really shine, but we can see that the bitwise and multiplication tricks come first, and the ternary if second. Finally, Webkit's Number
does similarly to V8's and the other methods fall behind, but are all close to each other. What are the takeaways? Browsers mostly manage to replace our conversions with simply the value 1
. This optimization will take place where we can mentally replace the boolean to a constant value. The Number
constructor is an intriguing anomaly - it severly falls behind in Firefox (91% slower!), while in Safari it is the fastest!
That above isn't a situation we'll ever encounter in real projects. So let's change our variables: the bool is now Math.random() < 0.5
. This yields a 50% chance of true
, 50% of false
. Do our results change? Let's run this benchmark to see.
Method | Chrome (V8) | Firefox (Spidermonkey) | Safari (Webkit) |
---|---|---|---|
Number(bool) |
1648.83 - 2.26% | 280.34 - 86.4% | 8014.69 |
bool ? 1 : 0 |
804.27 - 52.32% | 731.57 - 64.5% | 1294.02 - 83.85% |
+bool |
1670.79 - 0.95% | 2057.94 | 7753.99 - 3.25% |
bool | 0 |
1668.22 - 1.11% | 2054.17 | 7764.81 - 3.12% |
bool & 1 |
1675.52 - 0.67% | 2056.76 | 7193.08 - 10.25% |
~~bool |
1676.24 - 0.63% | 2056.18 | 7669.48 - 4.31% |
bool * 1 |
1686.88 | 2060.88 | 7751.48 - 3.28% |
The results are more consistent now. We see similar numbers for ternary if, bitwise, and multiplication methods across browsers, and the Number
constructor again performs the worst on Firefox. Ternary falls behind, as it generates branches. Safari seems to be our top performer overall, each method yielding blazing fast results!
Let's see now how branch prediction affects our results with the following benchmark, where we change our boolean variable to Math.random() < 0.01
, which means 1% true
, 99% false
.
Method | Chrome (V8) | Firefox (Spidermonkey) | Safari (Webkit) |
---|---|---|---|
Number(bool) |
1643.13 - 1.68% | 280.06 - 86.4% | 8071.65 |
bool ? 1 : 0 |
1590.55 - 4.83% | 1970.66 - 4.32% | 7119.59 - 11.8% |
+bool |
1662.09 - 0.55% | 2054.09 | 7762.03 - 3.84% |
bool | 0 |
1669.35 | 2051.85 | 7743.95 - 4.06% |
bool & 1 |
1661.09 - 0.61% | 2057.62 | 7454.45 - 7.65% |
~~bool |
1662.94 - 0.5% | 2059.65 | 7739.4 - 4.12% |
bool * 1 |
1671.28 | 2048.21 | 7787.38 - 3.52% |
Unexpected? Expected? I'd say the latter, because in this case branch prediction was successful in almost all cases, given the smaller difference between the ternary if and bitwise hacks. All other results are the same, not much else to say here. I'll still point out the horrific performance of Number
in Firefox - why?
This endeavour brings us back to the original question: how to convert bool to int in Javascript? Here are my suggestions:
- Use if statements, in general. Don't get smart - the browser will do better, usually, and usually means most of the situations. They are the most readable and clear out of all the methods here. While we're at readability, maybe use
if (bool)
instead of that ugly ternary! I wish Javascript had what Rust or Python have... - Use the rest when it's truly necessary. Maybe benchmarks in your project perform sub-standard, and you found that a nasty
if
causes bad performance - if that's the case, feel free to get into branchless programming! But don't go too deep in that rabbit hole, nobody will benefit from things like-1 * (a < b) + 1 * (a > b)
, believe me.
And some specifics:
- Avoid
Number(bool)
. While it is true that the Chromium platform (Chrome + Edge) has about 68% market share globally, Safari 19% and Firefox a mere 3.6%, there are enough other fast-performing methods that won't fully sacrifice a percentage of your users. Firefox has 7% desktop market share, which amounts to a sizable number of 173 million users. - In older benchmarks,
+bool
performed similarly bad toNumber
in Firefox, maybe take this in consideration, too - bitwise hacks and multiplication give consistently performant results across all browsers, in all situations.bool | 0
has the best chance to be familiar to other developers.
I will be forever grateful to you for reading until the end - this is my first longer, significant StackOverflow answer and it means the world to me if it's been helpful and insightful. If you find any errors, feel free to correct me!
EDIT: The previous benchmarking tool provided vague results, without an unit of measure. I've changed it, and also added benchmarks for Safari, which have influenced the conclusions.
- Defined the conversion because it's not truly clear what boolean to integer means. For example, Go does not support this conversion at all.

- 471
- 6
- 9
-
3upvoted for the effort but I can't think of a real use case when performance of such operation would matter :) – skwisgaar Feb 09 '21 at 10:15
-
@skwisgaar Completely agree, although I think this operation is mostly thought of using when people feel the need to optimize – Teodor Maxim Feb 14 '21 at 17:28
-
1Excellent post, but am trying to figure out the interpretation of the benchmark numbers, as you indicate 'operations/second'. In the V8 browser debugger of my 5yr old Acer laptop, the following million operations run in 36ms(!): `start=performance.now(); for (let i = 0; i < 1000000; i++) {let x = +(Math.random()<0.5);} end=performance.now(); console.log(end-start)`. What am I misinterpreting? – Trentium Feb 17 '21 at 22:48
-
Thanks for your reply! Running the benchmarks myself, the numbers look more like operations/_millisecond_. Although in both Chrome's and Firefox's DevTools the same benchmarks seem to run faster on my machine too - maybe JSBench is a bottleneck. I'll change the measure unit for now, but this must be looked further into. – Teodor Maxim Feb 18 '21 at 08:01
-
@TeodorMaxim just saw that you had replied... Sounds like it's not clear what JSBench is reporting... You might be best to create your own mini benchmark tool, as at least you'll know exactly what's being measured in addition knowing exactly how to interpret the results. – Trentium Feb 26 '21 at 17:34
-
Who cares about micro enhancements of performance that are not noticeable by humans? – Angel Aug 05 '22 at 08:35
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.

- 19,811
- 4
- 36
- 74

- 383
- 3
- 6
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;
}});

- 395
- 3
- 10
-
I've had two downvotes for this post. Why don't you explain why you downvoted it. Otherwise it's just a downvote without justification. – Nicholas R. Grant Sep 18 '17 at 03:01
-
199 times the results of jsperf just lead you up the premature optimisation path, optimising nanoseconds off a loop when you should be focussed on that ugly SQL statement instead. thanks for providing a few different ways to approach this – RozzA Oct 09 '17 at 21:25
-
What SQL statement? There's not a single query here. If you're referring to JSPerf, I was linking that from someone else's test. It's not my own. I honestly don't care about the performance aspect of this since it's a nothing operation. I created my own language that was nearly functionality identical to JS and I remember that casting to int was a stupidly fast operation. Climbing prototype chains was not. Which is why I'd still recommend the first way I did it, with a simple function that can be inlined by the compiler. – Nicholas R. Grant Oct 10 '17 at 16:52
-
The unary +
operator will take care of this:
var test = true;
// +test === 1
test = false;
// +test === 0
You'll naturally want to sanity-check this on the server before storing it, so that might be a more sensible place to do this anyway, though.

- 109,618
- 12
- 197
- 280

- 5,016
- 26
- 30
-
I have changed the comments to `===`, because `true == 1` is true even withou the "explicit conversion :-) `true === 1` instead is false. – xanatos Oct 19 '11 at 11:51
You can also add 0, use shift operators or xor:
val + 0;
val ^ 0;
val >> 0;
val >>> 0;
val << 0;
These have similar speeds as those from the others answers.

- 381
- 2
- 7
In my context, React Native where I am getting opacity value from boolean, the easiest way: Use unary + operator.
+ true; // 1
+ false; // 0
This converts the boolean into number;
style={ opacity: +!isFirstStep() }

- 180
- 2
- 8
+!!
allows you to apply this on a variable even when it's undefined
:
+!!undefined // 0
+!!false // 0
+!!true // 1
+!!(<boolean expression>) // 1 if it evaluates to true, 0 otherwise

- 24,585
- 15
- 82
- 105
You could do this by simply extending the boolean prototype
Boolean.prototype.intval = function(){return ~~this}
It is not too easy to understand what is going on there so an alternate version would be
Boolean.prototype.intval = function(){return (this == true)?1:0}
having done which you can do stuff like
document.write(true.intval());
When I use booleans to store conditions I often convert them to bitfields in which case I end up using an extended version of the prototype function
Boolean.prototype.intval = function(places)
{
places = ('undefined' == typeof(places))?0:places;
return (~~this) << places
}
with which you can do
document.write(true.intval(2))
which produces 4 as its output.

- 8,530
- 16
- 99
- 171
try
val*1
let t=true;
let f=false;
console.log(t*1);
console.log(f*1)

- 85,173
- 29
- 368
- 345
Boolean to integer conversion in JavaScript can be done in the following ways:
- Using
Number()
- Using Ternary
- Using Unary Operators
- Using Arithmetic Operators
- Using Bitwise Operators
- Using Bitwise Shift Operators
In previous answers some of these have already been covered, however, you can find some that are missing as follows:
// using arithmetic operators
true + 0; // 1
false + 0; // 0
true - 0; // 1
false - 0; // 0
true * 1 // 1
false * 1 // 0
true / 1; // 1
false / 1; // 0
// using bitwise operators
true & 1; // 1
false & 1; // 0
true | 0; // 1
false | 0; // 0
true ^ 0; // 1
false ^ 0; // 0
// using bitwise shift operators
true >> 0; // 1
false >> 0; // 0
true >>> 0; // 1
false >>> 0; // 0
true << 0; // 1
false << 0; // 0
These work because JavaScript internally coerces booleans to their integer equivalents when performing these operations.
An important point to note is that all these methods (except for using the ternary operator) can potentially return NaN
when you're unsure of the variable always having a boolean value.
Wrote a blog post for those interested in learning more.

- 4,204
- 1
- 17
- 13
I have tested all of this examples, I did a benchmark, and finally I recommend you choose the shorter one, it doesn't affect in performance.
Runned in Ubuntu server 14.04, nodejs v8.12.0 - 26/10/18
let i = 0;
console.time("TRUE test1")
i=0;
for(;i<100000000;i=i+1){
true ? 1 : 0;
}
console.timeEnd("TRUE test1")
console.time("FALSE test2")
i=0;
for(;i<100000000;i=i+1){
false ? 1 : 0;
}
console.timeEnd("FALSE test2")
console.log("----------------------------")
console.time("TRUE test1.1")
i=0;
for(;i<100000000;i=i+1){
true === true ? 1 : 0;
}
console.timeEnd("TRUE test1.1")
console.time("FALSE test2.1")
i=0;
for(;i<100000000;i=i+1){
false === true ? 1 : 0;
}
console.timeEnd("FALSE test2.1")
console.log("----------------------------")
console.time("TRUE test3")
i=0;
for(;i<100000000;i=i+1){
true | 0;
}
console.timeEnd("TRUE test3")
console.time("FALSE test4")
i=0;
for(;i<100000000;i=i+1){
false | 0;
}
console.timeEnd("FALSE test4")
console.log("----------------------------")
console.time("TRUE test5")
i=0;
for(;i<100000000;i=i+1){
true * 1;
}
console.timeEnd("TRUE test5")
console.time("FALSE test6")
i=0;
for(;i<100000000;i=i+1){
false * 1;
}
console.timeEnd("FALSE test6")
console.log("----------------------------")
console.time("TRUE test7")
i=0;
for(;i<100000000;i=i+1){
true & 1;
}
console.timeEnd("TRUE test7")
console.time("FALSE test8")
i=0;
for(;i<100000000;i=i+1){
false & 1;
}
console.timeEnd("FALSE test8")
console.log("----------------------------")
console.time("TRUE test9")
i=0;
for(;i<100000000;i=i+1){
+true;
}
console.timeEnd("TRUE test9")
console.time("FALSE test10")
i=0;
for(;i<100000000;i=i+1){
+false;
}
console.timeEnd("FALSE test10")
console.log("----------------------------")
console.time("TRUE test9.1")
i=0;
for(;i<100000000;i=i+1){
0+true;
}
console.timeEnd("TRUE test9.1")
console.time("FALSE test10.1")
i=0;
for(;i<100000000;i=i+1){
0+false;
}
console.timeEnd("FALSE test10.1")
console.log("----------------------------")
console.time("TRUE test9.2")
i=0;
for(;i<100000000;i=i+1){
-true*-1;
}
console.timeEnd("TRUE test9.2")
console.time("FALSE test10.2")
i=0;
for(;i<100000000;i=i+1){
-false*-1;
}
console.timeEnd("FALSE test10.2")
console.log("----------------------------")
console.time("TRUE test9.3")
i=0;
for(;i<100000000;i=i+1){
true-0;
}
console.timeEnd("TRUE test9.3")
console.time("FALSE test10.3")
i=0;
for(;i<100000000;i=i+1){
false-0;
}
console.timeEnd("FALSE test10.3")
console.log("----------------------------")
console.time("TRUE test11")
i=0;
for(;i<100000000;i=i+1){
Number(true);
}
console.timeEnd("TRUE test11")
console.time("FALSE test12")
i=0;
for(;i<100000000;i=i+1){
Number(false);
}
console.timeEnd("FALSE test12")
console.log("----------------------------")
console.time("TRUE test13")
i=0;
for(;i<100000000;i=i+1){
true + 0;
}
console.timeEnd("TRUE test13")
console.time("FALSE test14")
i=0;
for(;i<100000000;i=i+1){
false + 0;
}
console.timeEnd("FALSE test14")
console.log("----------------------------")
console.time("TRUE test15")
i=0;
for(;i<100000000;i=i+1){
true ^ 0;
}
console.timeEnd("TRUE test15")
console.time("FALSE test16")
i=0;
for(;i<100000000;i=i+1){
false ^ 0;
}
console.timeEnd("FALSE test16")
console.log("----------------------------")
console.time("TRUE test17")
i=0;
for(;i<100000000;i=i+1){
true ^ 0;
}
console.timeEnd("TRUE test17")
console.time("FALSE test18")
i=0;
for(;i<100000000;i=i+1){
false ^ 0;
}
console.timeEnd("FALSE test18")
console.log("----------------------------")
console.time("TRUE test19")
i=0;
for(;i<100000000;i=i+1){
true >> 0;
}
console.timeEnd("TRUE test19")
console.time("FALSE test20")
i=0;
for(;i<100000000;i=i+1){
false >> 0;
}
console.timeEnd("FALSE test20")
console.log("----------------------------")
console.time("TRUE test21")
i=0;
for(;i<100000000;i=i+1){
true >>> 0;
}
console.timeEnd("TRUE test21")
console.time("FALSE test22")
i=0;
for(;i<100000000;i=i+1){
false >>> 0;
}
console.timeEnd("FALSE test22")
console.log("----------------------------")
console.time("TRUE test23")
i=0;
for(;i<100000000;i=i+1){
true << 0;
}
console.timeEnd("TRUE test23")
console.time("FALSE test24")
i=0;
for(;i<100000000;i=i+1){
false << 0;
}
console.timeEnd("FALSE test24")
console.log("----------------------------")
console.time("TRUE test25")
i=0;
for(;i<100000000;i=i+1){
~~true;
}
console.timeEnd("TRUE test25")
console.time("FALSE test26")
i=0;
for(;i<100000000;i=i+1){
~~false;
}
console.timeEnd("FALSE test26")
console.log("----------------------------")
console.time("TRUE test25.1")
i=0;
for(;i<100000000;i=i+1){
~true*-1-1;
}
console.timeEnd("TRUE test25.1")
console.time("FALSE test26.1")
i=0;
for(;i<100000000;i=i+1){
~false*-1-1;
}
console.timeEnd("FALSE test26.1")
console.log("----------------------------")
console.time("TRUE test27")
i=0;
for(;i<100000000;i=i+1){
true/1;
}
console.timeEnd("TRUE test27")
console.time("FALSE test28")
i=0;
for(;i<100000000;i=i+1){
false/1;
}
console.timeEnd("FALSE test28")
Result
TRUE test1: 93.301ms
FALSE test2: 102.854ms
----------------------------
TRUE test1.1: 118.979ms
FALSE test2.1: 119.061ms
----------------------------
TRUE test3: 97.265ms
FALSE test4: 108.389ms
----------------------------
TRUE test5: 85.854ms
FALSE test6: 87.449ms
----------------------------
TRUE test7: 83.126ms
FALSE test8: 84.992ms
----------------------------
TRUE test9: 99.683ms
FALSE test10: 87.080ms
----------------------------
TRUE test9.1: 85.587ms
FALSE test10.1: 86.050ms
----------------------------
TRUE test9.2: 85.883ms
FALSE test10.2: 89.066ms
----------------------------
TRUE test9.3: 86.722ms
FALSE test10.3: 85.187ms
----------------------------
TRUE test11: 86.245ms
FALSE test12: 85.808ms
----------------------------
TRUE test13: 84.192ms
FALSE test14: 84.173ms
----------------------------
TRUE test15: 81.575ms
FALSE test16: 81.699ms
----------------------------
TRUE test17: 81.979ms
FALSE test18: 81.599ms
----------------------------
TRUE test19: 81.578ms
FALSE test20: 81.452ms
----------------------------
TRUE test21: 115.886ms
FALSE test22: 88.935ms
----------------------------
TRUE test23: 82.077ms
FALSE test24: 81.822ms
----------------------------
TRUE test25: 81.904ms
FALSE test26: 82.371ms
----------------------------
TRUE test25.1: 82.319ms
FALSE test26.1: 96.648ms
----------------------------
TRUE test27: 89.943ms
FALSE test28: 83.646ms

- 4,578
- 1
- 41
- 51
Put suggested methods in jsben.ch: https://jsben.ch/d33N1.
It gives different results every test, but the best methods in every test are bitwise operations: 0|bool
/ bool|0
/ 1&bool
/ 1&bool
/ ~~bool
.

- 11
- 1
supported in all browsers, supports input as boolean or as a string representation of a boolean
var yourVarAsStringOrBoolean;
yourVarAsStringOrBoolean = "true"; //1
yourVarAsStringOrBoolean = "True"; //1
yourVarAsStringOrBoolean = "false"; //0
yourVarAsStringOrBoolean = false; //0
var resultAsInterger = Number(JSON.parse(yourVarAsStringOrBoolean.toString().toLowerCase()));
Use Chrome console to check it, it works
Number(JSON.parse(false.toString().toLowerCase()));
Number(JSON.parse("TRUE".toString().toLowerCase()));

- 346
- 3
- 13
I know I'm a little late to do this, but you can use what's called a modulo. The modulo operator is represented by the percent (%) character in JS. Its goal is to give the remainder. So if we were to divide the number by 2%
, it would look for anything divisible than 2. If it isn't, then you have a remainder of 1, which will always be the case, so you know it's an odd. In this case, what you're going to do is first give the integer
any number you desire, in which case you want a 0
or 1
.
const integer = 0;
If you insert 1
it will print false
while 0
will print true
.
const isEven = (integer % 2) === 0;
if (isEven) {
console.log('true');
} else {
console.log('false');
}
I hope this helps.

- 1