자바스크립트에서는 변수가 함수가 될 수 있다.
그 밖에도 함수의 리턴값으로 함수가 올 수 있고, 함수의 인자로도 함수가 들어갈 수 있다.
위의 예시의 함수 val 처럼 다른 함수의 입력값으로 전달되어서 호출되는 함수를 Callback 함수 라고 한다.
자바스크립트에서 콜백함수가 사용되는 예시를 하나 살펴보자
아래 함수는 자바스크립트의 Array.prototype.filter() 함수이다.
filter() 함수는 첫번째 파라미터로 함수를 받도록 되어있다. 이 때, 입력받는 callback 함수는 element들을 살펴보며 true를 반환하면 요소를 유지하고, false를 반환하면 요소를 버린다.
filter() 함수의 사용 예시를 살펴보자.
words 배열의 단어들 중 길이가 6보다 긴 단어들만 반환된다.
이 때 filter() 함수의 입력값으로 콜백함수인 callback()함수가 들어간다.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
function callback(element) {
return element.length > 6;
}
newWords = words.filter(callback);
console.log(newWords);
// 결과 ["exuberant", "destruction", "present"]
기본적인 형태는 이런 식으로 가능하지만 코드의 효율성과 가독성을 위해 함수의 이름을 뺀 익명함수로 표현해보자.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
newWords = words.filter(function(element){
return element.length > 6;
});
console.log(newWords);
// 결과 ["exuberant", "destruction", "present"]
함수 함수 호출 자리에서 바로 콜백 함수를 넣어줄 수 있다.
하지만 가장 많이 쓰고, 편하고, 보기 좋은 방법은 Arrow function (화살표 함수)를 사용하는 것이다.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
newWords = words.filter((element) => {
return element.length > 6;
});
console.log(newWords);
// 결과 ["exuberant", "destruction", "present"]
화살표 함수에선 파라미터가 1개라면 괄호도 생략 가능하고, 코드가 길지 않다면 중괄호와 return도 생략 가능하다.
최대한 짧게 줄여본 코드는 다음과 같다.
newWords = words.filter(element => element.length > 6);
이번에는 filter()함수와 똑같이 작동하며 콜백함수를 사용하는 함수를 직접 구현하여 만들어보자.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
// filter()함수와 똑같이 동작하는 함수
function myfilter(origin, callback) {
var result = [];
for(var i=0; i<origin.length; i++) {
var current = origin[i];
if(callback(current)) {
result.pysh(current);
}
}
return result;
}
newWords = myfilter(words, element => element.length > 6);
console.log(newWords);
// 결과 ["exuberant", "destruction", "present"]
'JavaScript' 카테고리의 다른 글
[JavaScript] Promise 직접 만들기 (new Promise) (0) | 2022.05.23 |
---|---|
[JavaScript] async & await (0) | 2022.05.23 |
[JavaScript] 비동기(Asynchronous) - Promise (then, catch) (0) | 2022.05.23 |