How does it work (sort method)?

  • 0
    function compareNumeric(a, b) {
      if (a > b) return 1;
      if (a == b) return 0;
      if (a < b) return -1;
    let arr = [ 1, 2, 15 ];
    alert(arr);  // 1, 2, 15

    namely the line arr.sort (compareNumeric);
    the compareNumeric function is given above with parameters. but they are not here. and what is compared with what if they are not specified?
    JavaScript Anonymous, Aug 21, 2020

  • 2 Answers
  • 0
    For understanding, you can write it like this, the meaning will not change:

    arr.sort ((a, b) = & gt; compareNumeric (a, b));

  • 0
    The sort function is passed as an argument to the compareNumeric function.

    It is not the result of calling the compareNumeric function that is passed, otherwise there would be parentheses that signify a call, but it is the compareNumeric function itself that is passed (i.e. a pointer to it, i.e. its name).

    Next, the sort function, no matter how it is arranged internally, uses the compareNumeric function as it sees fit. Can call it with any parameters it wants. And since you cannot see how the sort function is implemented internally, you can only guess about it. But it is obvious that this is so, because when sorting, you will need to compare the elements of the array in pairs.

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!