[자바스크립트] callback 함수

김도현·2024년 3월 28일

JavaScript

목록 보기
6/7

✅ callback 함수란?

다른 함수의 인자로 전달되고 그 함수가 실행을 완료한 후에 호출되는 함수입니다. 또한 자바스크립트는 함수를 값(value)이 될 수 있습니다.

간단한 코드 예제를 보고 설명하겠습니다.

// 변수에 숫자라는 값을 가질 수 있습니다.
val = 1;// 변수에 조건문을 값으로 가질 수 없습니다
val = if(num) {
  			return num;}

// 변수에 함수는 값으로 가질 수 있습니다. first class Citizens
val = function(num) {
  			return num;
		}
// 
function fn(arg) {
 	arg(); 
}

fn(val); // val는 callback function이다.
  1. val이라는 변수는 함수를 저장하고 있다. 하지만 콜백함수는 아니다.
  2. val이라는 변수가 다른 함수의 입력값으로 전달 후 호출이(arg()) 된다면 val는 콜백함수이다.

✅ filter 함수를 활용하여 콜백함수 이해하기

const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

function callback(element) {
  console.log(element);
  if(element.length > 6) {
    	return true;
  }
  else {
    	return false;
  }
}

const newWords = words.filter(callback)

console.log(newWords);

// 코드를 좀 더 간략하게 하면 element.length > 6 이 코드 자체가 true false이기 때문에
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

function callback(element) {
	return element.length > 6;
}

const newWords = words.filter(callback)

console.log(newWords); 

// 익명함수로 사용하여 callback 함수를 사용할 수 있고
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

const newWords = words.filter(function (element) {
	return element.length > 6;
})

console.log(newWords); 

// 마지막으로 es6 문법으로도 변경하여 아주 간략하게 표현할 수 있다.
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

const newWords = words.filter(element => element.length > 6);

console.log(newWords);

// callback 함수를 활용하여 위 코드와 똑같이 실행되는 myFilter 만들어보기
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
//const newWords = words.filter(element => element.length > 6);

const myFilter = (arys, callback) => {
  let result = [];
  for(let i = 0; i < arys.length; i++) {
    const current = arys[i];
    if(callback(current) {
       		result.push(current);
       }
  }
}

const newWords = myFilter(words, element => element.length > 6);

console.log(newWords);
profile
개발 블로그!!

0개의 댓글