Logic not clicking

var number = [120, 2, 310, 23, 7, 13, 100];

number.sort(function(a,b){

    return a - b;
});
document.write(number);

i am not understanding this code from return could you please tell me mam whole working process of this code

1 Like

@mybloggrecord207 ,

This is a good question, you will get the reply soon

@mybloggrecord207 ,

If the sort(function(a,b)) returns negative value, a comes first by getting lower index than b.
a>b return -1 so, change position of the value to first(i.e, left side)

If sort(function(a,b)) returns zero then both get the same index and hence do not change place respect to each other but both gets sorted with all other elements.
a==b return 0 // no changes made their positions

If sort(function(a,b)) returns positive value, a gets higher index than b and hence a comes after b.

a<b returns positive value// higher value so it will come after b

for ex:120, 2, 310, 23, 7, 13, 100
let, a=120, b=2
a<b ==> 120<2 return -1 so change positions
2, 120,130…
2<120 ==>no modifications
120<130==> no modifications
2,120,130,23,7…
2<120 ==>correct, no modifications
120<130==> no modifications
130<23==> returns -1 so, change position
2,120,23,130…and so on until the problem is resolved.

I hope this will clarify your doubts.

2 Likes