-1

I'm learning javascript and a I got some questions about the sort method in javascript, yes, before you ask I've read the other questions, I understand this:

"Less than 0: "a" is sorted to be a lower index than "b". Zero: "a" and "b" are considered equal, and no sorting is performed. Greater than 0: "b" is sorted to be a lower index than "a"."

Thats from the main question about the sort() function, but what I don't understand is:

var array=[5, 2, 1, 10]

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

What is the purpose of the a and b as parameters in the function, what are value for the parameters that are going to be used during the function? It is told to return a-b but who are going to be a and b during the process? I'm not asking for the console.log() example. If a and b are my paremeter how is the function going to work if I am not even passing the value of a and b?

In other languages it would be neccesary to pass the values of a and b.

6

1 Answer 1

1

compareFunction: Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

What you are passing in the array.sort is a function known as the comparator function. What it will do is basically when it will sort your array if will sort it will compare two elements of the array at any given time and sort it according to the implementation details of the provided function.

Lets say you have an array [2 , 4, 3] Given your sort function will pass elements in the comparators to comparators 2,3 and you return the result 2 - 4 which is -2 and you already know < 0 means the the a elements needs to be on lower that is 2 will come first. it will compare 4 - 3 which is > 0 than means a needs to come after.

The Documentation has all the answers to your questions.

Sort Documentation on MDN

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

2 Comments

Thanks you Raunak Sett. So that means it doen't matter the name you give to the parameter of ther sort function, it wil still act like the compareFunction?
Yes its a reference for the sort function, it will call it giving the first parameter as the first element it wants to compare and the second parameter as the other element to compare against.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.