functions as parameters, higher-order functions

PHOTO EMBED

Tue Aug 13 2024 17:36:50 GMT+0000 (Coordinated Universal Time)

Saved by @thecowsays #javascript

const addTwo = num => {
  return num + 2;
}

const checkConsistentOutput = (func, val) => {
  let checkA = val + 2;
  let checkB = func(val);
  if (checkA === checkB) {
    return checkB;
  } else {
    console.log(`inconsistent results`);
  }
}

console.log(checkConsistentOutput(addTwo, 2));
content_copyCOPY

The basic function addTwo() takes whatever parameter for num is and adds 2. The higher-order function checkConsistentOutput uses this function as the first parameter and an integer of your choosing for the second parameter. The integer will have 2 added manually for checkA while checkB uses the addTwo() function. The results should be the same between both and line 8 checks this in the conditional--if it's true, then the result is returned and if it's false it logs to console our message. The final code on line 15 shows the higher-order function in use. It should display in the console whatever your integer was plus 2.

www.codecademy.com