함수의 겹괄호 표기

HS K·2023년 5월 5일

가끔 Map()함수나 reduce()함수처럼 함수의 기본형이 겹괄호로 이루어져 함수를 이해하기 어려운 경우가 있다.

그렇다면 왜 이렇게 복잡하게 생겼을까?

그 이유는 겹괄호([ ])는 선택적 인수를 표시하기 위해 사용된 것이기 때문이다. 이 구문은 함수 시그니처를 문서화할 때 사용되는 일반적인 표기법이다.

arr.map(callback(currentValue[, index[, array]])[, thisArg])

currentValue[, index[, array]]에서 대괄호가 겹쳐 있는 이유는 다음과 같다.

  1. index는 선택적 인수다. 따라서 대괄호([ ]) 안에 넣어 표시합니다
  • currentValue[, index]

  1. array는 index가 제공될 때만 선택적 인수로 사용할 수 있다.
    즉, index가 없으면 array도 사용할 수 없다. 이를 나타내기 위해 array도 대괄호([ ]) 안에 넣는다
  • currentValue[, index[, array]]

이 표기법은 다음과 같은 조합이 가능하다는 것을 나타낼 수 있다.

  • callback(currentValue): currentValue만 사용
  • callback(currentValue, index): currentValue와 index를 사용
  • callback(currentValue, index, array): currentValue, index, array를 모두 사용

그렇다면 예를 들어보자

arr.map(callback(currentValue, index, array), thisArg)

위 형태에서 대괄호([ ])를 추가하여 선택적 인수를 표시하면 원래의 형태가 된다.

arr.map(callback(currentValue[, index[, array]])[, thisArg])

profile
주의사항 : 최대한 정확하게 작성하려고 하지만, 틀릴내용이 있을 수도 있으니 유의!

0개의 댓글