views:

54

answers:

1

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.

+4  A: 

parseInt is the “most idiomatic” way, as it exactly describes what you want it to do. The drawback of parseInt is that it return NaN if you input a non-numeric string.

Another method is bitwise ORing by 0 (| 0), which also works for negative numbers. Moreover, it returns 0 when using it on a non-numeric string. Another advantage is that it is a bit faster than parseInt when using it on real numbers; it is slower when feeding it strings.

  • 12.4 | 0 outputs 12
  • -12.4 | 0 outputs -12
  • "12.4" | 0 outputs 12
  • "not a number" | 0 outputs 0
Marcel Korpel
It doesn't do exactly what I want. `parseInt("not an int, damnit")` returns `NaN`.
fmark
@fmark: Adjusted answer.
Marcel Korpel
The `|0` he mentioned does work pretty much what you want: strings are 0, `true` is 1, `28.3` is 28, `-28.3` is -28, NaN (as in e.g. `(+"foo")|0`) is 0, `undefined` is 0. Did I miss anything?
Amadan