1. 콜백(callback) 함수

: 함수에 인수 안에, 함수가 들어가 있는 것

[Node.js 강좌] 10. Callback 함수란 무엇인가 ?

cmd 창에서, node 만 입력하면, 해당 화면처럼 나온다.

그리고 아래의 코드들을 하나씩 입력해보자.

> console.log(1+1);
2
undefined
> a = [3,1,2]; console.log(a);
[ 3, 1, 2 ]
undefined
> a = [3,1,2]; a.sort(); console.log(a);
[ 1, 2, 3 ]
undefined
> a = [3,1,2]; function b(v1, v2){return v2-v1}; a.sort(b); console.log(a);
[ 3, 2, 1 ]
undefined
> a = [3,1,2]; function b(v1, v2){return v1-v2}; a.sort(b); console.log(a);
[ 1, 2, 3 ]
undefined
> a = [3,1,2]; function b(v1, v2){return 0}; a.sort(b); console.log(a);
[ 3, 1, 2 ]
undefined
> a = [3,1,2]; function b(v1, v2){console.log('c',v1,v2); return 0;}; a.sort(b); console.log(a);
c 1 3
c 2 1
[ 3, 1, 2 ]
undefined

JavaScript Array sort() Method

> a = [3,1,2]; function b(v1, v2){return v2-v1}; a.sort(b); console.log(a);
[ 3, 2, 1 ]
undefined
> a = [3,1,2]; function b(v1, v2){return v1-v2}; a.sort(b); console.log(a);
[ 1, 2, 3 ]
undefined
> a = [3,1,2]; function b(v1, v2){return 0}; a.sort(b); console.log(a);
[ 3, 1, 2 ]
undefined

// 를 통해서, 양수 음수 0 일 때 정렬의 순서가 바뀌는 것이 sort() 라는 것을 확인할 수 있다.

[JavaScript] 자바스크립트 콜백(callback)함수란?

콜백함수를 정의했지만, 콜백함수를 호출한 것은 우리가 아닌, sort() 라는 함수가 b 라는 함수를 호출하는 것이다.