2

Int Number | 0 will same as source number

But why Date.now() | 0 not same as Date.now()

let t = Date.now()
console.log((t | 0) === t)
Rajesh
  • 24,354
  • 5
  • 48
  • 79
bluelovers
  • 1,035
  • 2
  • 10
  • 22
  • 1
    `| 0` converts to a 32 bit integer. – VLAZ Mar 06 '20 at 09:13
  • Does this answer your question? [Using bitwise OR 0 to floor a number](https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number) – VLAZ Mar 06 '20 at 09:16
  • 1
    Did you confuse `Date.now() || 0` with `Date.now() | 0`? The two operators are very different. – Luaan Mar 06 '20 at 09:28
  • @Luaan not sure why you'd ever use `Date.now() || 0`. Surely, you will never get a falsy result from executing that method. – VLAZ Mar 06 '20 at 09:48
  • @VLAZ Of course not from `Date.now()` itself, I assume the `Date.now()` is just used here to provide a date value, that would be an argument/local in the actual code. – Luaan Mar 06 '20 at 09:58

1 Answers1

3

Bitwise operators operate on bits as represented by 32 zeros and/or ones. If the number being operated on is outside this range, the result will likely be unintuitive.

For bitwise OR, this limit is reached once the number is 2 ** 31 - 1:

const test = num => console.log((num | 0) === num);
test(2 ** 31 - 1)
test(2 ** 31)
test(2 ** 31 + 1)

Date.now returns the number of milliseconds between the epoch and now, which is a large number (1583486012561 or thereabouts), much larger than the upper limit of 2147483647.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320