Sort method (Javascript)

Hi Iam learning Javascript sort method but not able to understand from different sources.

if any one have few minutes then please explain how it works-
i mean how execution goes , which values are compare first and so on,
Please do not paste links I have visited it.

Have you visited this link?

Hey there,

it’s good advice to post some code and describe what you don’t understand.

return a-b;
1-which is and which is b
2-how execution goes (i mean which value will be compare with which one in order?
help shall be highly appreciated.

What do you think what a and b could be?

either 3 could be a or 1 colud be a,
but to specific what sort choose to be a or b

This can be answered by you fairly easy:

const arr=[3,1,5,4,2];
let iteration_count = 0;
arr.sort(function(a,b) {
  console.log('VALUE OF A: ', a);
  console.log('VALUE OF B: ', b);
  console.log('ITERATION #: ', iteration_count);
  return a-b;

Don’t be afraid to experiment :wink:


Thanks alot,
i was trying to understand its execution part , how it is comparing
first a=1;
second: a=5,b=1
third: should’nt be a=4 b=5???

JavaScript Array sort () Method The sort () method sorts the items of an array. The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down). By default, the sort () method sorts the values as strings in alphabetical and ascending order.

1 Like

that depends on the algorithm used, and the algorithm used depends on implementation

so your question is not really possible to andwer