📜 ⬆️ ⬇️

Vertical bar, then zero

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 “ | 0in 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; //     ( 3.3|0 ) === 3; //       ( 3.8|0 ) === 3; //  ,      ( -3.3|0 ) === -3; //         ( -3.8|0 ) === -3; //   Math.floor(-3.3) == Math.floor(-3.8) == -4 ( "3"|0 ) === 3; //        ( "3.8"|0 ) === 3; //        ( "-3.8"|0 ) === -3; //         ( NaN|0 ) === 0; // NaN    ( Infinity|0 ) === 0; //       , ( -Infinity|0 ) === 0; //    , ( null|0 ) === 0; //   null, ( (void 0)|0 ) === 0; //   undefined, ( []|0 ) === 0; //    , ( [3]|0 ) === 3; //        , ( [-3.8]|0 ) === -3; //       , ( [" -3.8 "]|0 ) === -3; //         , ( [-3.8, 22]|0 ) === 0 //        ( {}|0 ) === 0; //       ( {'2':'3'}|0 ) === 0; //    ( (function(){})|0 ) === 0; //       ( (function(){ return 3;})|0 ) === 0; //    

So, first of all, we have a convenient means of discarding the fractional part.


Secondly, we have a convenient means of converting various types to whole numbers.


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.

Source: https://habr.com/ru/post/172731/


All Articles