Higher Order Functions (1)
"Functions that return other functions"
Taimur Khan
🙋🏽♂️
Introductions 🏠
👨🏽🎓 Education :
- Geosciences + Physics, Skidmore College, NY, USA
🧑🏾💻 Work:
- Adsata - Founder/Lead Developer
- MLU Institute for Tech and Knowledge Transfer - Projectmanager
@thisistaimur
Today's Agenda ✅
- Revisiting Functional Programming
- Intro to Higher Order Functions
-
Higher Order Functions in JS
- Examples
- Common types
- Remarks/Questions
Revisiting ⨍unctional Programming ⚠️
- In JS --> Functions are objects
- Functional Programming --> Functions as parameters to other functions
- Also Return functions as values
- Functions are the bread and cake of JS programming
Revisiting ⨍unctional Programming ⚠️
Example
function greeting() {
console.log('Hello DCI!');
}
// Invoking the function
greeting(); // prints 'Hello DCI'
Higher Order Functions ❓(HOF)
- HOF style has roots in calculus (Or more specifically lambda calculus.)
-
In Mathematics or Programming, a higher-order function is a function that does at least one of the following:
- Takes one or more functions as arguments
- Returns a function as its result.
Higher Order Functions in JS 💡
- Taking another function as an argument is often referred as a callback function
- This method of passing in functions to other functions to use them inside is used in JavaScript libraries almost everywhere
Parameters vs Arguments in JS Functions. Source
1️⃣ Functions as Arguments
Higher Order Functions in JS 💡
1️⃣ Functions as Arguments : Example (1)
//define a global variable
var rand = Math.random();
//one takes in an argument
//and issues an alert with the x as it's argument.
function one(x) {
alert(x)
};
//two takes function callback as an argument
function two(callback) {
callback(rand);
};
two (one); //--> one goes into two
Higher Order Functions in JS 💡
1️⃣ Functions as Arguments : Example (2)
//one takes in an argument and issues
//an alert with the x as it's argument
function one(x) { alert(x); }
//two takes in an argument and a function
function two(randVar, callback) {
//two then passes the argument it took
//in to the function it took in
callback(randVar);
}
//one is the callback function here
two((Math.random()), one);
Higher Order Functions in JS 💡
- "Call a return"
- e doesn't have to be defined within the function d, can be outside too
2️⃣ Returning function as a result
function d() {
function e() {
alert('E');
}
return e;
};
d()();
//alerts 'E'
Higher Order Functions in JS 💡
Common Types of HOFs in JS
- map ()
- filter ()
- reduce()
Understanding map()
[GIF] map() functions. Source
Understanding filter()
[GIF] filter() functions. Source
More on ma(), filter (), and reduce()
Finishing Remarks 💬
Closures are really useful when we are dealing with higher-order functions, especially when we want to communicate state.
Questions and Comments
💬💭🗯
©Taimur Khan.2020.
Higher-Order Functions I
By taimurhk
Higher-Order Functions I
- 56