Still learning trying to understand how this function knows where to pull its parameter from

Still learning trying to understand how this function knows where to pull its parameter from
0

#1

Hello,

Could someone explain to me how the function with the parameter of (ltr) knows to use the result of the .split() as
its parameter? I understand that .every will check every index of the array. I just don’t understand how that function inside the every method knows to use the split method result as its parameter

function mutation(arr) {
  return arr[1].toLowerCase()
  .split('')
  .every(function(ltr){
    return arr[0].toLowerCase().indexOf(ltr) !== -1;
  });

}

thank you


#2

My guess is it’s probably something like this

var x = [1, 2, 3, 4];


x.copyOfEvery = function(aFunction){
	for(var i = 0; i < this.length; i++){
		if(!aFunction(this[i])){
     	return false;
     };
   }
   return true;
}


var answer = x.copyOfEvery(function(param){
  return param <= 4;
});

console.log(answer);

Basically the function that you pass to it gets stored as an argument. The native every function loops through the array, calling that argument/function each time the loop runs. The every function can look at the array simply by using this.

Once you use .split() the string automatically becomes an array, and since .every is a native array function, the new array you created automatically has .every.


#3

Hi @taylerRamsay,

I would look at the documentation on MDN for the function .every.

Essentially function .every that is native to all arrays is expecting what is called a callback function.

.every will take every item in the array, and run the callback function passing in the item as the first argument to that callback function.

At that point .every is evaluating whether the return values for each callback (on each item in the array) is a truthy value. If it is a truthy value it returns true, else it returns false. Hope this helps.


#4

Thanks guys that was very helpful!