This code snippet is from w3schools JavaScript section. I am trying to figure out what
points.sort( function(a, b) {
return 0.5 - Math.random()
});
The sort
callback is supposed to return a value <0, 0 or >0 to indicate whether the first value is lower than, equal to or higher than the second; sort
uses that to sort the values. 0.5 - Math.random()
returns a value between -0.5 and 0.5 randomly, satisfying the expected return values and resulting in an essentially randomly shuffled array.
Note that this shouldn't be the preferred method to shuffle; since the return value is random and not internally consistent (e.g. it tells sort
that foo < bar
, bar < baz
and foo > baz
), it may make Javascript's sort algorithm very inefficient. A Fisher-Yates shuffle for instance is pretty trivially implemented and likely more efficient.