매개변수 parameter

DOYOUNG·2023년 5월 19일
0

javascript

목록 보기
10/17
post-thumbnail

함수의 매개변수

1) 기본값 매개변수

function add(a = 2, b = 4) {
  console.log(`${a} + ${b}`);
  return a + b;
}

console.log(
  add(),
  add(1),
  add(1, 3)
);

2) arguments

arguments : 함수 내에서 사용가능한 지역 변수

  • 배열의 형태를 한 객체
  • 함수 호출 시 전달된 모든 인수들을 배열 형태로 가짐
function add(a, b) {
  console.log('1.', arguments); // 1. [1,3,5,7]
  console.log('2.', arguments[0]); // 2. 1
  console.log('3.', typeof arguments); // 3. object
  return a + b;
}

console.log(
  '4.', add(1, 3, 5, 7) // 4. 4
);
function add(a, b) {
  for (const arg of arguments) {
    console.log(arg);
  }
  return a + b;
}

console.log(
  add(1, 3, 5, 7)
);

for ~ of 문을 사용할 수 있음.
화살표 함수에서는 arguments 사용 불가능함.

profile
프론트엔드 개발자 첫걸음

0개의 댓글