Another question asked about the meaning of the code snippet a >>> 0
in Javascript. It turns out that it is a clever way of ensuring that a variable is a unsigned 32-bit integer.
This is pretty neat, but I don't like it for two reasons.
- The intent of the expression is not clear, at least not to me.
- It does not work for negative numbers
This leads me to ask: What is the most idiomatic way of converting an arbitrary value to an "integer" in Javascript? It should work for signed integers, not just non-negative numbers. Cases where this breaks due to the fact that integers are just floats in disguise in Javascript are acceptable, but should be acknowledged. It should not return undefined
or NaN
in any case (these are not integers), but return 0
for non-numeric values.