-2

I came across the .every() method today and found this example code to explain how it works:

var ages = [32, 33, 16, 40];

function checkAdult(age) {
    return age >= 18;
}

function myFunction() {
    document.getElementById("demo").innerHTML = ages.every(checkAdult);
}

The result of myFunction() is false, and I understand what the method is doing (going through each value of the array and checking if the value is >= 18, but I don't understand how the .every() method is able to use the age parameter in its return statement without age being declared in the method call.

Does the method somehow automatically know that it should be referencing the index of the array it's looking at? That's the only explanation I can come up with, but I can't find any explanation of this online.

  • 2
    [The documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/every) explains this. `every` calls the function `checkAdult` with the parameter given in `ages` - "every" single element in that array. – Reinstate Monica Cellio Nov 22 '16 at 16:28
  • "that is never given a value" — It is given a value. Look at what `every` does. – Quentin Nov 22 '16 at 16:30
  • it is called [API](https://en.wikipedia.org/wiki/Application_programming_interface). – Nina Scholz Nov 22 '16 at 16:30
  • `ages.every(function (age) { return checkAdult(age); })` - makes more sense? It passes a function which takes one argument and returns a result (the result of `checkAdult(age)`). Well… `checkAdult` already is a function that takes one argument and returns a result, so just get rid of the superfluous anonymous function wrapper → `every(checkAdult)`. – deceze Nov 22 '16 at 16:34
  • I just realized I misspoke...my bad. What I meant to say was that I don't understand how `checkAdult()` is called within `.every()` without having some value assigned to its `age` parameter. I know that parameters are optional in JS, but since `checkAdult()` is using its parameter in the return statement I would think it would need to have a value passed to it when being used in the `.every()` method. – Nick Martini Nov 22 '16 at 16:45
  • Do you understand what a *callback* function is? Do you understand how `ages.every(function (age) ...)` gets its `age` argument? – deceze Nov 22 '16 at 16:47
  • @deceze Correct, I don't understand how it gets the `age` argument. Which I guess also means that I don't understand callback functions lol. – Nick Martini Nov 22 '16 at 16:51
  • @NickMartini basically like this: `Array.prototype.every = function(fn){ for(var i = 0; i – Thomas Nov 22 '16 at 17:42

1 Answers1

1

without age being declared in the method call.

It is declared in the method call. You simply aren't looking at the method call.

checkAdult is passed as an argument to every. The code inside every calls that function and passes it a value.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335