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.
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.
Type conversion (or typecasting) means transfer of data from one data type to another. Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like JavaScript) automatically converts data types. The source code can also explicitly require a conversion to take place.
In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With