🍀 함수 호출
함수 호출 연산자 내에는 0개 이상의 인수를 쉼표로 구분해서 나열한다. 함수를 호출하면 현재의 실행 흐름을 중단하고 호출된 함수로 실행 흐름을 옮긴다.
매개변수에 인수가 순서대로 할당된다.
📝 매개변수(parameter)와 인수(argument)
매개변수를 통해 인수를 전달한다. 인수는 값으로 평가될 수 있는 표현식이어야 한다. 인수는 함수를 호출할 때 지정하며, 개수와 타입에 제한이 없다.
// 함수 선언문
function add(x, y) {
return x + y;
}
// 함수 호출
// 인수 1과 2가 매개변수 x, y에 순서대로 할당되고 함수 몸체의 문들이 실행된다.
var result = add(1, 2);
매개변수는 함수 몸체 내부에서 변수와 동일하게 취급된다. 즉, 함수가 호출되면 함수 몸체 내에서 암묵적으로 매개변수가 생성되고 일반 변수와 마찬가지로 undefined로 초기화된 이후 인수가 순서대로 할당된다.
- 매개변수의 스코프(유효 범위)는 함수 내부이다.
함수는 매개변수의 개수와 인수의 개수가 일치하는지 체크하지 않는다.
- 함수를 호출할 때 매개변수의 개수만큼 인수를 전달하는 것이 일반적이지만 그렇지 않은 경우에도 에러가 발생하지 않는다.
- 인수가 부족해서 인수가 할당되지 않은 매개변수의 값은 undefined 이다.
- 매개변수보다 인수가 더 많은 경우 초과된 인수는 무시된다.
- 초과된 인수는 버려지는 것이 아니다. 모든 인수는 암묵적으로 arguments 객체의 프로퍼티로 보관된다.
// 함수 선언문
function add(x, y) {
console.log(arguments);
return x + y;
}
add(2, 5, 7);
arguments 객체는 함수를 정의할 때 매개변수 개수를 확정할 수 없는 가변 인자 함수를 구현할 때 유용하게 사용된다.
arguments 객체에 대해서는 뒤에서 살펴볼 예정이다!
📝 인수 확인
- 자바스크립트 함수는 매개변수와 인수의 개수가 일치하는지 확인하지 않는다.
- 자바스크립트는 동적 타입 언어다. 따라서 자바스크립트 함수는 매개변수의 타입을 사전에 지정할 수 없다.
자바스크립트의 경우 함수를 정의할 때 적절한 인수가 전달되었는지 확인할 필요가 있다.
// 함수 선언문
function add(x, y) {
if (typeof x !== 'number' || typeof y !== 'number') {
throw new TypeError('인수는 모두 숫자 값이어야 합니다.');
}
return x + y;
}
console.log(add(2)); // TypeError: 인수는 모두 숫자 값이어야 합니다.
console.log(add('a', 'b')); // TypeError: 인수는 모두 숫자 값이어야 합니다
함수 내부에서 적절한 인수가 전달되었는지 확인하더라도 부적절한 호출을 사전에 방지할 수 없고 에러는 런타임에 발생한다.
타입스크립트와 같은 정적 타입을 선언할 수 있는 자바스크립트의 상위 확장을 도입해서 컴파일 시점에 부적절한 호출을 방지할 수 있게 하는 것도 하나의 방법이다.
앞의 예제에서 인수의 개수는 확인하고 있지 않지만 arguments 객체를 통해 인수 개수를 확인할 수도 있다. 또는 인수가 전달되지 않는 경우 단축 평가를 사용해 매개변수에 기본값을 할당하는 방법도 있다.
function add(x, y, z) {
x = x || 0;
y = y || 0;
z = z || 0;
return x + y + z;
}
console.log(add(1, 2, 3)); // 6
console.log(add(1, 2)); // 3
console.log(add(1)); // 1
console.log(add()); // 0
ES6에서 도입된 매개변수 기본값을 사용하면 함수 내에서 수행하던 인수 체크 및 초기화를 간소화할 수 있다. 매개변수 기본값은 1) 인수를 전달하지 않았을 경우와 2) undefined를 전달한 경우에만 유효하다.
// ES6 매개변수 기본값
function add(x = 0, y = 0, z = 0) {
return x + y + z;
}
console.log(add(1, 2, 3)); // 6
console.log(add(1, 2)); // 3
console.log(add(1)); // 1
console.log(add()); // 0
📝 매개변수의 최대 개수
ECMAScript 사양에서는 매개변수의 최대 개수에 대해 명시적으로 제한하고 있지 않다. 하지만 물리적 한계는 있으므로 자바스크립트 엔진마다 매개변수의 최대 개수에 대한 제한은 있다.
매개변수가 많아지면 함수에 호출해야할 인수의 순서를 고려해야하므로 실수를 발생시킬 가능성이 높아진다.
매개변수의 개수나 순서가 변경되면 함수의 호출 방법도 바뀌므로 함수를 사용하는 코드 전체에 영향을 준다.
=> 매개변수가 많으면 유지보수성이 나빠진다.
이상적인 매개변수의 개수는 0개이고 매개변수는 적을수록 좋다.
이상적인 함수는 한 가지 일만 해야하며 가급적 작게 만들어야 한다.
매개변수는 3개 이상 넘지않는 것을 권장하고, 만약 그 이상의 매개변수가 필요하다면 하나의 매개변수를 선언하고 객체를 인수로 전달하는 것이 유리하다.
객체를 인수로 사용하는 경우 프로퍼티 키만 정확히 지정하면 매개변수의 순서를 신경쓰지 않아도 된다.
또한 명시적으로 인수의 의미를 설명하는 프로퍼티 키를 사용하니 코드의 가독성도 좋아지고 실수를 방지할 수 있다.
※ 함수 외부에서 함수 내부로 전달한 객체를 함수 내부에서 변경하면 함수 외부의 객체가 변경되는 부수 효과(side effect)가 발생한다.
📝 반환문
함수는 return 키워드와 표현식(반환값)으로 이뤄진 반환문을 사용해 실행 결과를 함수 외부로 반환(return) 할 수 있다.
함수 호출은 표현식이다. 함수 호출 표현식은 return 키워드가 반환한 표현식의 평과 결과, 즉 반환값으로 평가된다.
반환문의 두 가지 역할
- 반환문은 함수의 실행을 중단하고 함수 몸체를 빠져나간다.
- 반환문 이후에 다른 문이 존재하면 그 문은 실행되지 않고 무시된다. - 반환문은 return 키워드 뒤에 오는 표현식을 평가해 반환한다.
- return 키워드 뒤에 반환값으로 사용할 표현식을 명시적으로 지정하지 않으면 undefined가 반환된다.
반환문은 생략한 경우에는?
함수는 함수 몸체의 마지막 문까지 실행한 후 암묵적으로 undefined를 반환한다.
function sayHi() {
var a = '1';
// return 문을 반환하지 않음
}
console.log(sayHi()); // undefined
return 키워드와 반환값으로 사용할 표현식 사이에 줄바꿈이 있다면?
세미콜론 자동 삽입 기능에 의해 세미콜론이 추가되어 의도치 않은 결과가 발생할 수 있다!
function plus(x, y) {
return // 세미콜론 자동 삽입 기능(ASI)에 의해 세미콜론이 추가된다.
x + y; // 무시된다.
}
console.log(plus(3,4)); // undefined
반환문은 함수 몸체 내부에서만 사용할 수 있다. 전역에서 반환문을 사용하면 문법 에러(SyntaxError)가 발생한다.
🍀 퀴즈
- 함수의 매개변수의 스코프(유효 범위)는 ( )이다.
정답: 함수 내부
- 인수가 부족해서 인수가 할당되지 않은 매개변수의 값은 ( ) 이다.
정답: undefined
- 초과된 인수는 버려지는 것이 아니다. 모든 인수는 암묵적으로 ( ) 객체의 프로퍼티로 보관된다.
정답: arguments
- 함수 외부에서 함수 내부로 전달한 객체를 함수 내부에서 변경하면 함수 외부의 객체가 변경된다. (O, X)
정답: O
함수 외부에서 함수 내부로 전달한 객체를 함수 내부에서 변경하면 함수 외부의 객체가 변경되는 부수 효과(side effect)가 발생한다.
- 함수에서 return 반환문을 생략하면 어떻게 될까?
정답: 함수는 함수 몸체의 마지막 문까지 실행한 후 암묵적으로 undefined를 반환한다.
'JavaScript' 카테고리의 다른 글
[JavaScript] 변수 - 변수란?, 식별자, 변수 선언 (0) | 2023.11.01 |
---|---|
[JavaScript] 함수 - 참조에 의한 전달과 외부 상태의 변경 (2) | 2023.10.27 |
[JavaScript] 함수 - Funtion 생성자 함수, 화살표 함수(개념만) (0) | 2023.10.27 |
[JavaScript] 함수 - 함수 생성 시점과 함수 호이스팅 (0) | 2023.10.27 |
[JavaScript] 함수 - 함수를 사용하는 이유, 함수 리터럴, 함수 정의 (0) | 2023.10.23 |