Array Sort method with functions question

So I do not understand whats going on inside the function. I get that the points.sort goes through the points array and arranges them in order, but after that another function is added? inside a function? What are the parameters exactly and what is happening in them. You can add a function into a method just by adding (function())? can someone break down this line of code please

var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction() {
  points.sort(function(a, b){return a - b}); // this line
  document.getElementById("demo").innerHTML = points;
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate 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.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

sort() is one of those methods that work with a callback, and you can write a function like that or with arrow function

You can read more about how sort works here:

1 Like

JavaScript has first class functions, which means you can pass a function as a parameter to another function. In this case, you pass function(a, b){return a - b} as a parameter to sort().

sort() uses the passed function to decide how it sorts. You can read the “Syntax” and “Description” sections of @ilenia’s MDN link to understand how it uses this function.

1 Like

Ahhh thanks for the tip :+1:
Much appreciated

I have reviewed the link you suggested. Thank you for your suggestion. There is a subject I want to ask.
function (a, b) {return a - b} selects and compares any two elements from the array. It first chose the numbers 40 to 100, and in comparison he found that the number 40 was less than the number 100. It sent the value -1 as an argument to the sort () method. Due to the capabilities of the sort () method, he placed the number 40 in the first row in the series. It then compared the number 40 with the number 1, and this time he placed the number 1 in the first place. I’m curious about this. Under what conditions will this comparison process be terminated and the pairs to be compared are selected randomly, will not an infinite loop occur here?

Could you demonstrate the sorting process in the example given in the example as applied for all elements.

it stops when everything is sorted

the how it is sorted it is not possible to tell as it varies depending on the implementation of the browser or environment you are using