Functional programming

Functional programming
0

#1
function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}
ascendingOrder([1, 5, 2, 3, 4]);

I didn’t understand the above code that how the function is working with values a & b.
Can someone explain me??


#2

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

sort() by default considers values as strings and sorts them alphabetically. For example “20” will be greater than “100”, because 2 is greater than 1. That is why for sorting numbers compare function(a,b) is used.

For example if you have 2 numbers a=40 and b=100. a-b will return a negative number, that indicates 40 is less than 100. Similarly this is applied for all the elements of the array.

Very good explanation about this is given in the below link.
JavaScript Array sort() Method