1. 콜백함수의 이해
자신이 아닌 다른 함수에, 인수로서 전달된 함수를 의미함
원하는 때에 호출하여 실행시킬 수 있다.

⇒ 해당 코드에서는
main 함수에 매개변수로서 전달된 sub 함수가 콜백함수다!
⇒ 람다로 사용가능!
2. 콜백함수의 활용
// 2. 콜백함수의 활용
function repeat(count) {
for (let idx = 1; idx <= count; idx++) {
console.log(idx);
}
}
function repeatDouble(count) {
for (let idx = 1; idx <= count; idx++) {
console.log(idx * 2);
}
}
function repeatTriple(count) {
for (let idx = 1; idx <= count; idx++) {
console.log(idx * 3);
}
}
repeat(5);
repeatDouble(5);
repeatTriple(5);- 반복되는 비슷한 기능의 함수를 여러 개 만들어야 할 때, 콜백함수를 활용하여 코드를 줄일 수 있다.
function repeat(count, callBack) {
for (let idx = 1; idx <= count; idx++) {
callBack(idx);
}
}
repeat(5, (idx) => {
console.log(idx);
});
repeat(5, (idx) => {
console.log(idx * 2);
});
repeat(5, (idx) => {
console.log(idx * 3);
});
Share article