# 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,

Have you visited this link? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Hey there,

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

Hi,
`arr=[3,1,5,4,2];
arr.sort(function(a,b){
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) {
iteration_count++;
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 2 Likes

Thanks alot,
i was trying to understand its execution part , how it is comparing
first a=1;
b=3;
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