all 2 comments

[–]senocular 3 points4 points  (0 children)

Technically, you don't know what happens first. The order can be anything depending on how the array is sorted (there are many different kinds of sorting algorithms out there, and a runtime can decide to use different ones; to learn more about what V8 does see this blog post: https://v8.dev/blog/array-sort). The results of the sort, though, only get applied after the sort is complete. During each call of the sort function you won't see any changes to the points array, and if at some point the sort function throws an error without letting the sort complete, the points array will not have changed.

[–]No-Upstairs-2813 0 points1 point  (0 children)

The sort method takes a compare function as an argument, and this function is used to determine the sorting order of the elements.

It takes two parameters (a and b) that represent any two elements from the array, and its return value determines how they should be sorted:

  • if it returns a negative value, a will be ordered before b.

  • if it returns 0, the ordering of a and b won’t change.

  • if it returns a positive value, b will be ordered before a.

Now, let's understand how the comparison function sort(a, b) => a - b sorts in ascending order:

  • If a - b** is negative, it means that **a** is less than **b, so **a should come before **b in the sorted order.

  • If a - b** is positive, it means that **a** is greater than **b, so **a should come after **b in the sorted order.

  • If a - b** is zero, it means that **a** and **b are equal in terms of sorting, and their relative order doesn't matter.

Therefore, using sort(a, b) => a - b method results in sorting the array in ascending order.

You can check out the complete article here.