An entity that supports being passed as an argument, is mutable, can be assigned to a variable or returned from a function.
For example:
function sumOperation(values){
const total = 0;
values.forEach(x=> total += x);
return total;
}
function isNegative(value){
return value<0;
}
function sumIsPositiveCallback(result){
console.log("success! sum is: ",result);
}
function sumIsNegativeCallback(result){
console.log("failure! sum is: ",result);
}
function doOperationThenDoCallback(successCallback,failureCallback,operation, hasError,values)
{
var result = operation(values);
if(hasError(result)){
failureCallback(result)
}
else{
successCallback(result);
}
}
(function(){
console.clear();
console.log("Passing Functions as Arguments");
const goodValues = [1,2,3]
doOperationThenDoCallback(sumIsPositiveCallback,sumIsNegativeCallback,sumOperation,isNegative,goodValues);
const badValues = [1,2,-4]
doOperationThenDoCallback(sumIsPositiveCallback,sumIsNegativeCallback,sumOperation,isNegative,badValues);
})();
One use-case for mutating a function is extending a function when you don't have access to the source code. Like a thrid party library that you want to make fit you needs.
function myCurveFunction(x){
let y = x * x / 3;
return y;
}
function thridParty_getVector(curveFunction, x){
return [x, curveFunction(x)];
}
(function(){
console.log("Mutating a Function");
var oldFunction = thridParty_getVector;
thridParty_getVector = function(curve, values){
if(typeof(values) === typeof(0)){
return oldFunction(curve, values);
}
if(typeof(values) === typeof([])){
return values.map(value=>oldFunction(curve, value));
}
}
console.log(thridParty_getVector(myCurveFunction,1));
console.log(thridParty_getVector(myCurveFunction,[1,2,3]));
})();
See it running here: https://codepen.io/DevEarley/pen/QWLrgrp