Higher-Order Functions Fundamentals
Higher-Order Functions
A function that accepts and/or returns another function is called a higher-order function.
It's higher-order because instead of strings, numbers, or booleans, it goes higher to operate on functions. Pretty meta.
With functions in JavaScript, you can
Store them as variables
Use them in arrays
Assign them as object properties(methods)
Pass them as arguments
Return them from other functions
Functions Operate on Data
Strings Are Data
sayHi = (name) => `Hi, ${name}!`;
result = sayHi('Unity');
console.log(result); // Hi, Unity!
Numbers Are Data
double = (x) = > x * 2;
result = double(4);
console.log(result); // 8
Booleans Are Data
getClearance = (allowed) => (allowed ? 'Access granted' : 'Access denied');
result1 = getClearance(true);
result2 = getClearance(false);
console.log(result1); // Access granted
console.log(result2); // Access denied
Objects Are Data
getFirstName = (obj) => obj.firstName;
result = getFirstName({
firstName: 'Bjarne'
});
console.log(result); // 'Bjarne'
Arrays Are Data
len = (array) => array.length;
result = len([1, 2, 3]);
console.log(result); // 3
What makes them first-class? You can pass them around, store them in variables and arrays, use them as inputs for calculations. You can use them like any piece of data.