Click here to Skip to main content
15,900,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I don't really understand them at all. The most I know is this:

JavaScript
function Test(a, b) {
alert(a + b);
}

Test("Hello ", "World!");
//Alerts "Hello World!"

I understand what a and b is in this function. But in the next example, I have no idea what a and b are. Take a look:

JavaScript
function Sort() {
var arr = [31, 1, 71, 500];
arr.sort(function(a, b) {return a - b});
alert(arr);
}
//Alerts "1,31,71,500". Without the parameters, it sorts as "1,31,500,71".
But I still don't know what a and b are, or how they managed to sort it correctly.

What I have tried:

Nothing. Nobody on Sololearn understood my question, so now i'm here. xD
Posted
Updated 1-Aug-18 15:50pm
v2

1 solution

sort function of javascript array object take 1 parameter or no parameter.

what would happen if no paramerter? it sort alphabetically. in order to tell javascript howyou want to sort you need to pass a function as parameter to sort function. The parameter function takes two arguments and either zero or positive non zero or negative non zero (haha)

funtion comp(a, b) {
 return a-b; // 0 means equal, negative means a is small.
}
arr.sort(comp);

in your example your function is anonymous. this fuction is not reusable and will be lost after execution


I will give you an example, so that you can understand anonymous function.

Let's say we have a function that produce "hello world". But the function itself do not render the result. Instead function uses provided mechanism to represent data.
function HelloWorld(func) {
 // we will use this func to render the result
 var result="Hello World";
 func(result); // we are using func as a function 
}

// now let's use HelloWorld function to utilize data; 
function DisplayToDiv(res) {
 document.getElementById("divid").innerHtml = res;
} 

// call the function
HelloWorld(DisplayToDiv); 

// let's write the next command to output as console result 

HelloWorld(function /*name is not required*/(res){
 console.log(res);
});

// another example
HelloWorld(alert); // does alert look familiar to you?


Hope this helps


Oh!! by the way, this function that you pass is called call back function
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900