The fact is, a lot of functions are not a good function
Let's take a look at a example
function tenSquared() {
return 10 * 10;
}
tenSquared();
What about a 9 squared function? about 125 quared
We don't want to write functions like that, repeat is the worst thing in programing.
What could we do instead?
We write a more generalizable code piece
function squareNum(num) {
return num * num;
}
squareNum(10);
squareNum(5);
We can use num to represent any actual number withou repeating, that is what the parameter is for
parameters
means we don't need to decide what data to run our functionality on until we run the function
- Then provide an actual value
argument
when we run the function
- We may not want to decide exactly what some of our funcionality is until we run our function
We could generalize our function, so we pass in our specific instruction only when we run copyArrayAndManipulate
// This is our higher-order function
function copyArrayAndManipulate(array, instructions) {
const output = [];
for(let i = 0; i < array.length; i++) {
output.push(instructions(array[i]));
}
return output;
}
// This is callback function
function multiplyBy2(input) {
return input * 2;
}
const result = copyArrayAndManipulate([1,2,3], multiplyBy2);