Given the following code

var arr = [1, 2, 3, 4, 5]; function compareRandom(a, b) { return Math.random() - 0.5; } arr.sort(compareRandom); alert( arr ); // элементы в случайном порядке, например [3,5,1,2,4] 

Each time it places the elements of the array in a different order, but why not the same effect if we remove -0.5 from the function?

 var arr = [1, 2, 3, 4, 5]; function compareRandom(a, b) { return Math.random(); } arr.sort(compareRandom); alert( arr ); // [1, 2, 3, 4, 5] 

    1 answer 1

    Math.random() returns values ​​in the interval [0; 1)

    A comparator passed to the .sort function must return three options:

    1. <0 - if the first number is less than the second, and you do not need to change
    2. 0 - if the numbers are the same
    3. > 0 - if the first number is greater and you need to change them

    When using return Math.random(); only two options 2 and 3 can return, so the final array is sorted in descending order.

    When using Math.random() - 0.5 interval is shifted by 0.5 to the left and becomes equal to [-0.5, 0.5) , which allows you to get all three options described, and, therefore, to obtain a random position of the elements.

    • Well, then, in theory, the array should look like this: [2, 3, 4, 5, 1]? - Novikov Maxim
    • @NovikovMaksim, in what case? - Grundy