The title, expressed in
words , was needed only for searchable finding. But it will be a question of the role of the
character construct “ | 0 ” in JavaScript.
For the first time, I noticed it when I translated the
FAQ about asm.js and read the
specifications of this subset of the JavaScript language.
There, " | 0 " serves, for example,
to specify the type of value returned from a function: when we
saw " | 0 " after a value, it means that we have a significant integer.
Suddenly, I noticed the
construction “ | 0 ”
in the example code on Github, where the conversion to a whole number of the result of dividing by 1024² took place.
')
Then my eyes opened, and I saw wonderful opportunities:
( 3|0 ) === 3;
So, first of all, we have a convenient means of discarding the fractional part.
- In relation to negative numbers, it is useful in that a fractional number is converted not to the nearest smaller integer (increasing in absolute value), as it would have happened after “ Math.floor () ”, but to the nearest smaller modulo integer (increasing in value ). Often this is exactly what is required.
- In relation to positive numbers, it is useful, especially because the construction of " | 0 " is more than an order of magnitude shorter compared to " Math.floor () ". Therefore, it can and should cause developers to get used no less than the “ $ () ” entry in jQuery, which I mentioned four days ago , that no one voluntarily goes back to “ document.getElementsByClassName () ”, for example .
Secondly, we have a convenient means of converting various types to whole numbers.
- It can pick out integers (and discard the fractional part of fractional numbers), extracting them from the strings (with the initial and final spaces discarded) and even from single-element arrays.
- In relation to the data of all other types (which can not be extracted), this tool acts as a universal zeroer. Often this is exactly what is required.
Observing the effect of this tool, you should compare it with the method
(“ + ” before the value), which is recommended
in “JavaScript Garden” (and after it
in “JavaScript Garden” ) for conversion to number.
With such a comparison, it is immediately clear that plus converts
to a fractional number, making possible such exotic variants of fractional numbers as minus infinity (obtained, for example,
from “ + [“ -Infinity ”] ”) or NaN
(from “ + {} ” ), whereas “ | 0 ” converts
to an integer , and therefore exotic variants are reset.
I recommend this technique to be widely used in your javascript code as needed.