JavaScript

Higher-Order Functions

WebDevLee 2021. 10. 19. 19:38

이 글은 자바스크립트의 Higher-Order Functions(고차함수)에 관한

개념 및 문법을 정리하기 위해 작성하였습니다.



 

< Introduction >

We are often unaware of the number of assumptions we make when we communicate with other people in our native languages. If we told you to “count to three,” we would expect you to say or think the numbers one, two and three. We assumed you would know to start with “one” and end with “three”.
With programming, we’re faced with needing to be more explicit with our directions to the computer. Here’s how we might tell the computer to “count to three”:
for (let i = 1; i<=3; i++) {
  console.log(i);
}

In programming, we can accomplish “abstraction” by writing functions : Higher-Order Functions.
using more abstraction in our code allows us to write more modular code which is easier to read and debug.

 

  • Higher-order functions : functions that accept other functions as arguments and/or return functions as output.

 

 


< Functions as Data >

Javascript functions behave like any data type in the language.
This means we can assign functions to variables, and we can reassign them to new variables.


In JavaScript, functions are first class objects. This means that, like other objects you’ve encountered, JavaScript functions can have properties and methods. You can see more about the methods and properties of functions 
in this documentation.
: http://: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

 

ex)

const announceThatIAmDoingImportantWork = () => {
    console.log("I’m doing very important work!");
};

const busy = announceThatIAmDoingImportantWork;

console.log(busy.name);   //   announceThatIAmDoingImportantWork
busy();   //   I’m doing very important work!

 

 


< Functions as Parameters >

A higher-order function is a function that either accepts functions as parameters, returns a function, or both.

 

  • We call the functions that get passed in as parameters and invoked callback functions.
  • When we pass a function in as an argument to another function, we pass in the function itself by typing the function name without the parentheses ( ) (that would evaluate to the result of calling the function)

 

ex)

const timeFuncRuntime = funcParameter => {
   let t1 = Date.now();
   funcParameter();
   let t2 = Date.now();
   return t2 - t1;
}
const addOneToOne = () => 1 + 1;
 
timeFuncRuntime(addOneToOne);
// Anonymous functions can be arguments too!
timeFuncRuntime(() => {
  for (let i = 10; i>0; i--){
    console.log(i);
  }
});

 

 


< Introduction to Iterators >

The built-in JavaScript array methods that help us iterate are called iteration methods.
(One of the higher-order functions)

 

 


< The .forEach() Method >

To execute some code for each element.

 

  • .forEach() takes an argument of callback function.(Common)
  • During the execution, the current element is passed as an argument to the callback function.(Common)
  • The return value for .forEach() will always be undefined.

 

ex)

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Arrow Function
fruits.forEach(fruit => {
  console.log(`I want to eat a ${fruit}`);
})
// Function Expressions
fruits.forEach(function(fruit) {
  console.log(`I want to eat a ${fruit}`);
})
// Function Declaration
function printFruit(element) {
  console.log(`I want to eat a ${element}`);
}
fruits.forEach(printFruit);
  • You can use a function declaration, function expression, and arrow function.(Common)

 

 


< The .map() Method >

To get a new array after executing some code.

 

  • .map() takes an argument of callback function.(Common)
  • During the execution, the current element is passed as an argument to the callback function.(Common)
  • You should use return keyword to get a new array.

 

ex)

const numbers = [1,2,3,4,5];
const bigNumbers = numbers.map(number => {
  return number * 10;
})

console.log(numbers);   //   [1,2,3,4,5]
console.log(bigNumbers);   //   [10,20,30,40,50]

 

 


< The .filter() Method >

To get a new array after filtering out certain elements from the original array.

 

  • .map() takes an argument of callback function.(Common)
  • During the execution, the current element is passed as an argument to the callback function.(Common)
  • Callback function should return true or false using element.
  • The elements that cause the callback function to return true are added to the new array.

 

ex)

const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door']; 
 
const shortWords = words.filter(word => {
  return word.length < 6;
});

console.log(words);   //   ['chair', 'music', 'pillow', 'brick', 'pen', 'door']
console.log(shortWords);   //   ['chair', 'music', 'brick', 'pen', 'door']

 

 


< The .findIndex() Method >

To get the index of the element that evaluates to true.

 

  • .map() takes an argument of callback function.(Common)
  • During the execution, the current element is passed as an argument to the callback function.(Common)
  • If there isn’t a single element in the array that satisfies the condition in the callback,
    or we don't use return keyword, then .findIndex() will return -1

 

ex)

const jumbledNums = [123, 25, 78, 5, 9]; 
 
const lessThanTen = jumbledNums.findIndex(num => {
  return num < 10;
});

console.log(lessThanTen);   //   3 
console.log(jumbledNums[3]);   //   5

 

 


< The .reduce() Method >

To get a single value after iterating through the elements of an array.

 

  • .map() takes an argument of callback function.(Common)
  • reduce() returns the result value of a cumulative calculation.
  • reduce() can take 2 argument
    1. callback function
    2. initialValue (Optional)
  • The callback function can take 4 argument
    1. accumulator : The previous return value of the callback.
    2. currentValue : Current element to process
    3. currentIndex (Optional)
    4. array (Optional)

 

For more information, Please reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

 

ex)

const numbers = [1, 2, 4, 10];
 
const summedNums = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
})
 
console.log(summedNums)   //   17

// We can set a initial Value
const summedNums = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
}, 100)

console.log(summedNums)   //   117