0

I have started learning javascript a few days ago and I have a bad time understand what these lines:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

What is a and b equal to in this function? Thank you very much for your help in advance

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
  • `a` and `b` will be assigned elements from the array. In order to sort the array, pairs of elements are compared. See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description): *"If `a` and `b` are two elements being compared, then: [...] "* – Felix Kling Oct 17 '18 at 22:01
  • 2
    I suggest that you add a `console.log(a, b);` line before `return b-a`. Can you determine where the output values come from? – Code-Apprentice Oct 17 '18 at 22:02
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Osama Oct 17 '18 at 22:05

1 Answers1

0

The sorting algorithm implement by sort() will call the specified function with various combinations of elements from array to determine which element should go first in the order. The two chosen element for comparison will be a and b.

Kon
  • 4,023
  • 4
  • 24
  • 38