Higher Order Function
In JavaScript, functions are first-class objects, so they can be assigned to variables
Function expressions cannot be used before assignment
square(7); -> Reference Error
const square = function (num) { // Function expression assigning a function to variable square return num * num; }; // Since the variable square is assigned a function, it's a first-class object, and you can use the function call operator () output = square(7);Since functions have the characteristics of first-class objects, they can be assigned as values of object properties as shown below
const cat = { name: 'nabi', age: 3, cry: function () { console.log('miaow..'); }, };
2. Understanding Higher Order Functions
Definition: A function that can take a function as an argument and return a function
A function passed as an argument to another function (caller) is called a callback function
The higher order function (caller) that receives the callback function can call (invoke) this callback function inside, and can decide whether to execute the callback function depending on the condition
A function that returns a function is called a currying function, and when using this term, it's sometimes limited to 'a function that takes a function as an argument'. In other words, higher order functions include currying functions.
In summary, both 'a function that returns a function' and 'a function that takes a function as an argument' are used as higher order functions
a. When taking another function as an argument
b. When returning a function
c. When taking a function as an argument and returning a function
3. Built-in Higher Order Functions
In JavaScript, there are several built-in higher order functions, and some of the array methods are representative higher order functions.
The filter method of arrays is a method that 'filters' elements that meet a certain condition among all elements of the array
The specific condition that serves as the filtering criterion is passed as an argument to the filter method, and the form is a function.
Therefore, the filter method is a higher order function because it takes a function specifying the filtering condition as an argument.
When using filter, remember the following process
Each element of the array
If it is true according to a certain logic (function)
It is classified separately (filter)
Last updated