JavaScript Higher-Order Function

Taking a function as an argument:

function applyFunctionToArray(arr, fn) {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    result.push(fn(arr[i]));
  }
  return result;
}

const numbers = [1, 2, 3, 4, 5];

function double(x) {
  return x * 2;
}

const doubledNumbers = applyFunctionToArray(numbers, double);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

Leave a Comment