2
var anArray = [ 5, 4, 8 , 1, 3] ; 

anArray.sort(function (a,b){return a - b}); 

1) Can someone run me through how JavaScript will execute the sort method with function that is passed as a parameter ?

  • It will compare 5 with 4 then because it's positive, 4 will be before 5. Then it will compare 5 with every other number but 1 and 3 are also smaller than 5. So how java script know which position to put them before 5?

  • then it will compare 4 with every other number and 8 with every other number etc... how java script do this? I want to do it with pen and paper.

2) why the function that is passed as an parameter is nameless ?

thank you.

2

1 Answer 1

3
  1. Exactly how the comparator function will be called — that is, the sequence of values passed in — is not defined by the specification of the language. It completely depends on the particular JavaScript implementation and (probably) on the values in the array being sorted. Suffice to say that the sorting algorithm calls your function when it wants to compare two numbers, and that's that.

    The function is expected to return a value that's negative, zero, or positive, indicating that the ordering of the two numbers should be that the first one comes first, that either can come first, or that the second one should come first. A quick way to do that is to just subtract the second number from the first.

  2. The function in your sample code is an anonymous function. It needs no name because it will be bound to a symbol in the receiving function as a result of the function call itself. You can give the function a name if you want to.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.