3 ms·
Bitwise operations coerce the value to a int32. If a value cannot be reasonably coerced to an int (e.g. 'foo'), you get zero. It's basically the same as parseIn
by grayrest 16y ago
Bitwise operations coerce the value to a int32. If a value cannot be reasonably coerced to an int (e.g. 'foo'), you get zero. It's basically the same as parseInt(x,10) but is generally faster, you don't need to remember the radix, and you don't get NaN. The downside is that trying to coerce numbers outside int32 will give incorrect answers.
The other way to write it is 0|num which has the advantage of only applying one bitwise op.
These tend to crop up most often in graphics oriented libraries.
- euroclydon 16y agoThanks. Anything quicker than parseFloat?
- grayrest 16y agoYou'd have to bench it, but the only thing I could think of that'd be faster is the standard +num coercion that's also used in the code snippet. Unfortunately, that does generate NaNs. Edit: Double checked the spec (it's quite readable) and the main difference is that + will coerce ignoring whitespace while parseFloat will ignore leading whitespace and parse leading digits. E.g. var x = '1.23foo'; parseFloat(x) is 1.23; +x is NaN. Neither looks like it should be faster than the other.