Search code examples
javascriptperformancemathfloor

Difference between ~~ and Math.floor()


As I see in examples, the functionality if ~~ and Math.floor is the same. Both of them round a number downward (Am I think correct?)

Also I should mention that according to this test ~~ is faster than Math.floor: jsperf.com/math-round-vs

So I want to know, is there any difference between ~~ and Math.floor?


Solution

  • Yes, bitwise operators generally don’t play well with negative numbers. f.ex:

    ~~-6.8 == -6 // doesn’t round down, simply removes the decimals
    
    Math.floor(-6.8) == -7
    

    And you also get 0 instead of NaN, f.ex:

    ~~'a' == 0
    
    Math.floor('a') == NaN