#Day55 of #100DaysOfCode
Today I went to town and I did some shopping and had a great Saturday dinner
I also managed to publish the International Women’s Day event which I would be organizing in our very own MongoDB office ![]()
Today I studied Higher-Order Functions, I did these before and at that time they were hard to grasp but Codecademy lessons are great, I have started to get the hang of it. Some Notes below:
Introduction
Higher-Order Functions help add a level of abstraction to programming. These functions can accept other functions as arguments and/or return functions as output.
Functions as Data
In Javascript, functions are first class objects. This means, Javascript functions can have properties and methods. Since functions are a type of object, they have properties such as .length and .name , and methods such as .toString() .
Read more about the methods and properties of functions in the Mozilla documentation.
Functions are special because they can be invoked, but can also be treated like any other type of data.
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :( ');
}
}
};
// Assigned a function with a longer name to a new variable
const isTwoPlusTwo = checkThatTwoPlusTwoEqualsFourAMillionTimes;
isTwoPlusTwo();
console.log(isTwoPlusTwo.name)
Functions as Parameters
Since functions can behave like any other type of data in JavaScript, it can accept other functions as parameters.
A higher-order function is a function that either accepts functions as parameters, returns a function, or both! Such functions that get passed in as parameters are called callback functions. Callback functions get invoked during the execution of the higher-order function.
const higherOrderFunc = param => {
param();
return `I just invoked ${param.name} as a callback function!`
}
const anotherFunc = () => {
return 'I\'m being invoked by the higher-order function!';
}
higherOrderFunc(anotherFunc);
In the above function, highOrderFunc accepts a single parameter param. This function is invoked inside the body and also returns a string telling us the name of the callback function.
High-Order Functions can also have anonymous functions as arguments
higherOrderFunc(() => {
for (let i = 0; i < 0; i++){
console.log(i);
}
});
Review
-
Abstraction allows writing complicated code in a way that’s easy to reuse, debug, and understand for human readers.
-
We can work with functions the same way we work with any other type of data, including reassigning them to new variables.
-
JavaScript functions are first-class objects, so they have properties and methods like any other object.
-
Functions can be passed into other functions as parameters.
-
A higher-order function is a function that either accepts functions as parameters, returns a function or both.
That is all for today… ![]()