x && 1 does it.
for(x=0; x<5; x++) { console.log(x & 1) }
Writes:
0 1 1 1 1
This is a logical AND but Javascript's type rules appear to keep the result as a number.
But you should consider how many JS coders would instinctively understand this.
Preferring legibility to terseness, I would personally use the ternary operator:
x == 0 ? 0 : 1
... although the option you've asked to avoid is also highly legible:
Number(Boolean(x))
You seem to imply that this might be slower than the alternatives.
- I see no reason why this would be slow.
Number and Boolean are language built-ins that do very simple operations that we'd expect to be incredibly cheap - Premature optimisation is the root of all evil. You should only worry about this kind of micro-optimisation if your code is running unacceptably slowly. This operation would only have such an effect if it was running millions of times in a loop. If that was the case you could easily tell if another option was cheaper, just by trying it.
Note that your requirement:
turn it to 0 if the value is 0 or to turn it to 1 if it greater than zero
... does not specify what you want to happen if x is negative. This answer allows you to tune accordingly.
+or!), or does it need to be strictly bitwise operators only ?1-!xshould also do the trickNumber(Boolean(x))can be written as+!!x(unary operation)