Search code examples
javascriptparameterscallbacknestedexecution

How do the argument parameters work for these nested functions?


I am working improving my understanding of higher order functions and callbacks within Javascript. My code here gives me the output I'm looking for, but I'm not exactly sure how it's all working. My confusion is how the arguments work for callback within filterArray and how that gets passed through to eitherCallback which actually takes two parameters: callback1 and callback2, which are functions. Technically callback (in filterArray) is taking a number, so how does that get passed through to eitherCallback if eitherCallback's two parameters are stored as functions? I'm super new to Javascript so your time and kindness is appreciated. :)

function eitherCallback(callback1, callback2) {
  return num => callback1(num) || callback2(num); 
}

function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i += 1) {
    if (callback(array[i], i, array)) newArray.push(array[i]);
  }
  return newArray;
}
const arrOfNums = [10, 35, 105, 9];
const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
const over100 = n => n > 100;
const intSqRtOrOver100 = eitherCallback(integerSquareRoot, over100);
console.log(filterArray(arrOfNums, intSqRtOrOver100)); // should log: [105, 9]

Solution

  • The relevant point here is just that eitherCallback takes two callbacks (that is, two functions) and returns another function. Functions in JavaScript are "first class" values - which doesn't just mean they can be passed as arguments to other functions, they can also be returned from functions. You can see very clearly that eitherCallback returns a function from its single line with the return statement - what it returns is

    num => callback1(num) || callback2(num)
    

    which is a function expression. Specifically, it's a function that calls callback1 and* callback2, and returns the "logical or" of their results.

    So the callback given to filterArray does indeed take a single numeric parameter. That function here is eitherCallback(integerSquareRoot, over100) - a function that takes a number and tells you if it either has an integer square root or is over 100.

    To summarise: eitherCallback takes the two callbacks it's passed and returns another callback - this resulting callback is the one passed to filterArray. Please let me know if I can make anything clearer.

    *strictly speaking it doesn't always, due to short-circuiting of ||. But this doesn't matter unless the functions have side effects, which the ones used here don't