> For the complete documentation index, see [llms.txt](https://shhn0509.gitbook.io/javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shhn0509.gitbook.io/javascript/js-upgrade/callback-function-1/undefined.md).

# 콜백 함수의 기능

콜백 함수는 2가지 기능을 가진다. 1) 처리의 위임, 2) 나중 작업 등록이다.&#x20;

## 1.처리의 위임&#x20;

&#x20;처리의 위임은 메소드에 인자로 함수를 전달하여 원래 메소드가 동작하는 기능을 바뀌게 하는 것이다.&#x20;

&#x20;제일 대표적인 적은 `Array.sort()` 메서드에 콜백함수를 전달하는 것이다.&#x20;

```javascript
function sortNumber(a,b){
    // 위의 예제와 비교해서 a와 b의 순서를 바꾸면 정렬순서가 반대가 된다.
    return b-a;
}
var numbers = [20, 10, 9,8,7,6,5,4,3,2,1];
alert(numbers.sort(sortNumber)); // array, [20,10,9,8,7,6,5,4,3,2,1]
```

{% hint style="info" %}
sortNumber 함수는 아래 함수를 간단하게 만든 것이다.&#x20;

```javascript
function sortNumber(a, b) {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  return 0;
}
```

{% endhint %}

## 2. 나중 작업 등록&#x20;

콜백은 비동기처리에서도 유용하게 사용된다. 시간이 오래걸리는 작업이 있을 때 이 작업이 완료된 후에 처리해야 할 일을 콜백으로 지정하면 해당 작업이 끝났을 때 미리 등록한 작업을 실행하도록 할 수 있다.&#x20;

```javascript
$.get('./datasource.json.js', function(result){
        console.log(result);
    }, 'json');
```
