List of solutions
There are three solutions I would like to propose. All of them convert any value to 0
(if 1
, true
etc.) or 1
(if 0
, false
, null
etc.):
v = 1*!v
v = +!v
v = ~~!v
and one additional, already mentioned, but clever and fast (although works only for 0
s and 1
s):
Solution 1
You can use the following solution:
v = 1*!v
This will first convert the integer to the opposite boolean (0
to True
and any other value to False
), then will treat it as integer when multiplying by 1
. As a result 0
will be converted to 1
and any other value to 0
.
As a proof see this jsfiddle and provide any values you wish to test: jsfiddle.net/rH3g5/
The results are as follows:
-123
will convert to integer 0
,
-10
will convert to integer 0
,
-1
will convert to integer 0
,
0
will convert to integer 1
,
1
will convert to integer 0
,
2
will convert to integer 0
,
60
will convert to integer 0
,
Solution 2
As mblase75 noted, jAndy had some other solution that works as mine:
v = +!v
It also first makes boolean from the original value, but uses +
instead of 1*
to convert it into integer. The result is exactly the same, but the notation is shorter.
Solution 3
The another approach is to use ~~
operator:
v = ~~!v
It is pretty uncommon and always converts to integer from boolean.