0

Wondering what the << does in this:

Math.random() * Math.pow(36, 2) << 0

Not sure how to use that in practice.

Lance
  • 75,200
  • 93
  • 289
  • 503
  • you could also wrap everything in `Math.floor()` or use `| 0` at the end. its basically just flooring. – GottZ Dec 20 '17 at 22:14
  • 1
    to be honest i'd have written it like that: `Math.random() * 36 ** 2 | 0` Math.pow is obsolete in my humble opinion – GottZ Dec 20 '17 at 22:16
  • good to know :)) – Lance Dec 20 '17 at 22:21
  • 1
    keep in mind '| 0' will not protect you against integer overflows. it really casts a double to an int. you could get a negative number by doing this: `3498723498723 | 0` – GottZ Dec 20 '17 at 22:23

2 Answers2

1

It truncates the number / converts it to an integer. You can test this for yourself:

console.log(12.345 << 0); // 12

— This question is very similar to Why does a shift by 0 truncate the decimal?

Jim Smart
  • 2,559
  • 2
  • 7
  • 2
1

Take a look at this

a = Math.pow(36, 2)
1296
a = Math.random() * a
477.5906135469167
a = a << 0
477
isherwood
  • 58,414
  • 16
  • 114
  • 157