Understanding callbacks on array's methods

9523 단어 jstech

Callback function


You see callback functions. Especially when you deal with arrays, there are built-in methods that receive a callback function. For example,
myArray.map(callback);
myArray.filter(callback);
myArray.forEach(callback);
myArray.find(callback);
What is 'callback' here? To understand how these functions(methods) work and are used, let us see functions from the very basics.

Basic function


sum.js
/**
 * add two numbers
 * @param {number} a - augend
 * @param {number} b - addend
 * @return {number} a + b - sum
 */
function sum(a, b) {
  return a + b;
} 

const result = sum(1, 2);
console.log(result);  // output: 3

Funtion using expression


You can assign functions to variables.
sum.js
const sum = function(a, b) {
  return a + b;
} 

const result = sum(1, 2);
console.log(result);  // output: 3

Arrow function


You don't need to write 'function' everytime you define a funtion. You can substitute 'function' by arrow. Here is the steps
  • Remove 'function' BEFORE the arguments
  • Add '=>' AFTER the arguments
  • sum.js
    const sum = (a, b) => {
      return a + b;
    } 
    
    const result = sum(1, 2);
    console.log(result);  // output: 3
    

    Arrow function with one argument


    In case it has only one argument, you can omit parentheses.
    double.js
    const double = a => {
      return 2 * a;
    } 
    
    const result = double(3);
    console.log(result);  // output: 6
    

    You now know what 'callback function' is


    Now you know what's going on with built-in functions defined on arrays and objects.
    double.js
    const items = [1, 2, 3];
    const result = items.map(item => {return 2 * item;});
    console.log(result); 
    

    Implicit return


    Just one more thing. You can omit brackets{} and 'return' whenever there is only one expression inside the arrow function. Note however that you can take advantage of implicit return from ONLY arrow functions.
    double.js
    const items = [1, 2, 3];
    const result = items.map(item => 2 * item);
    console.log(result); 
    
    Now, You got what you're familiar with:)

    좋은 웹페이지 즐겨찾기