I've seen some javascript functions with parameters that are not pre-defined, but still work. Doubt came up with the function below. The myFunction()
function calls the pessoas.sort()
method, which in turn receives an auto-invoked function as argument. This has the parameter a
and b
. Why does it even work those not having been previously defined? Does the JS engine interpret them alone? How can this be done on other occasions and with other parameters?
var pessoas = [
{country:"Brazil", name:"Lucas"},
{country:"EUA", name:"Jhon"},
{country:"Japan", name:"Sushi"}]
function myFunction() {
pessoas.sort(function(a, b){return a.name - b.name});
show();
}
function show() {
document.getElementById("demo").innerHTML =
pessoas[0].country + " " + pessoas[0].name + "<br>" +
pessoas[1].county + " " + pessoas[1].name + "<br>" +
pessoas[2].country + " " + pessoas[2].name;
}
<div id="demo"></div>
<button onclick="myFunction()">Mostrar</button>