Understanding callbacks on array's methods
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
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:)
Reference
이 문제에 관하여(Understanding callbacks on array's methods), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/satto/articles/a0de792b4691c6텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)