1 - JSHP - Callbacks and Higher Order Functions
1 - JSHP - Callbacks and Higher Order Functions
const num = 3;
function multiplyBy2 (inputNumber){
const result = inputNumber*2;
return result;
}
const name = "Will"
— Thread of execution (parsing and executing the code line after line)
— Live memory of variables with data (known as a Global Variable
Environment)
Running/calling/invoking a function
const num = 3;
function multiplyBy2 (inputNumber){
const result = inputNumber*2;
return result;
}
const name = "Will"
When you execute a function you create a new execution context comprising:
1. The thread of execution (we go through the code in the function line by line)
2. A local memory ('Variable environment') where anything defined in the function is stored
We keep track of the functions being called in JavaScript
with a Call stack
Takes no input
Returns 10*10
How do we do it?
tensquared
function tensquared(){
return 10*10;
}
tensquared(); // 100
Now let's create a function that returns 9 squared
function ninesquared(){
return 9*9;
}
ninesquared(); // 81
Now 8 squared...and so on
...
We have a problem - it's getting repetitive, we're breaking our DRY principle
function squareNum(num){
return num*num;
}
squareNum(10); // 100
squareNum(9); // 81
We’ve generalized our function
Answer these:
function copyArrayAndMultiplyBy2(array) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(array[i] * 2);
}
return output;
}
const myArray = [1,2,3]
const result = copyArrayAndMultiplyBy2(myArray)
What if want to copy array and divide by 2?
function copyArrayAndDivideBy2(array) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(array[i] /2);
}
return output;
}
const myArray = [1,2,3]
const result = copyArrayAndDivideBy2(myArray);
Or add 3?
function copyArrayAndAdd3(array) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(array[i] +3);
}
return output;
}
const myArray = [1,2,3]
const result = copyArrayAndAdd3(myArray);
function multiplyBy2(input) {
return input * 2;
}
They can co-exist with and can be treated like any other
javascript object
function multiplyBy2(input) {
return input * 2;
}
const result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);
function multiplyBy2(input) {
return input * 2;
}
const result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);
The outer function that takes in the function (our callback) is a higher-order function
Higher-order functions