1

https://stackoverflow.com/a/15106541/10757573

In this thread, the solution uses the following code:

var randomProperty = function (obj) {
    var keys = Object.keys(obj)
    return obj[keys[ keys.length * Math.random() << 0]];
};

In the comments from the answer, one user explained the bitwise shift as:

It's more as a shorthand of parseInt(keys.length * Math.random(), 0)


Can anyone explain how the bitwise shift left 0 is the same as parseInt, or how it works in general, please?

I'm using this syntax, and it works well, but I don't understand what it's doing.

w2-
  • 19
  • 5
  • 3
    "*I'm using this syntax, and it works well, but I don't understand what it's doing.*" then how do you know it works *well*? – VLAZ Sep 12 '19 at 05:06
  • Also, `parseInt(keys.length * Math.random(), 0)` makes no sense - you parse the value into base zero? What is any number in base zero represented as? – VLAZ Sep 12 '19 at 05:08
  • @VLAZ `radix: 0` actually has special behaviour: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt – Dai Sep 12 '19 at 05:09

2 Answers2

2

The usual idiom for selecting a random array element is

array[Math.floor(array.length * Math.random())]

What this code is doing is using << 0 as a shortcut for Math.floor(). keys.length * Math.random() will be a floating point number. The << operator requires that its operands be integers, so it will automatically convert that float to an integer, and it does this by rounding down, just like Math.floor() does.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Performing value << 0 in JavaScript has the effect of coercing value into an integer when value is a non-integer. This is needed in this case because Math.random() returns a floating-point number, which cannot be used as an integer indexer (keys is an Array so it's indexed by an integer).

parseInt( /*string:*/ textValue, /*radix:*/ 0 ) does not convert a number to "base 0", instead when radix == 0, the parseInt function will parse textValue as base 10 unless textValue starts with 0x in which case it will parse it as base 16.

Dai
  • 141,631
  • 28
  • 261
  • 374