[JavaScript] 6. 함수

BANG·2025년 8월 19일

JS

목록 보기
6/8

함수 (Functions)

  • 0개 이상의 이름이 있는 매개변수를 가질 수 있음
  • 함수에 지역적인 변수를 선언할 수 있음
  • 반환 문이 없으면 (혹은 값이 없는 반환이 사용되면), JavaScript는 undefined을 반환
  • 매개변수로 지정된 것보다 많거나 적은 변수를 사용해서도 함수를 호출할 수 있음
  • 예상되는 매개변수를 전달하지 않고 함수를 호출하면 undefined로 설정
  • 예상보다 많은 매개변수를 전달하면 추가로 전달되는 매개변수를 무시함
add(); // NaN
// add(undefined, undefined)와 동등합니다.

add(2, 3, 4); // 5
// 처음의 두 수가 더해집니다. 4는 무시됩니다.
  • JavaScript에는 명명된 매개 변수가 없음
  • 객체를 편리하게 하나로 합치고, 분해할 수 있는 구조 분해 할당을 사용하여 구현할 수 있음
// 중괄호({ })에 유의. 객체를 분해
function area({ width, height }) {
  return width * height;
}

// 여기서 중괄호({ })는 새로운 객체를 생성
console.log(area({ width: 2, height: 3 }));

익명 함수

  • 익명 함수(이름이 없는 함수)를 만들 수 있음
  • 이름없는 함수들은 다른 함수의 인자로 전달하거나 함수를 호출하는 데 사용할 수 있는 변수에 즉시 할당되거나 다른 함수에서 반환됨
// 괄호 앞에 함수명이 없음을 주목
const avg = function (...args) {
  let sum = 0;
  for (const item of args) {
    sum += item;
  }
  return sum / args.length;
};

// 괄호 앞에 함수명이 없음을 주목
const avg = (...args) => {
  let sum = 0;
  for (const item of args) {
    sum += item;
  }
  return sum / args.length;
};
// function avg() {}와 같이 이름을 붙인 함수 선언과 의미적으로 같음

// 단순히 표현식을 반환할 때, `return`을 생략
const sum = (a, b, c) => a + b + c;

구조 분해 할당

  • 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식
var a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20

// Stage 4(finished) proposal
({ a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 });
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}
  • 배열 구조 분해
var foo = ["one", "two", "three"];

var [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
  • 변수에 기본값을 할당하면, 분해한 값이 undefined일 때 그 값을 대신 사용
var a, b;

[a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7
  • 하나의 구조 분해 표현식만으로 두 변수의 값을 교환할 수 있음
var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
  • 일부 반환 값 무시하기
  • 나머지 구문을 이용해 분해하고 남은 부분을 하나의 변수에 할당할 수 있습
function f() {
  return [1, 2, 3];
}

var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3

var [a, ...b] = f();
console.log(a); // 1
console.log(b); // [2, 3]
  • 객체 구조 분해
var o = { p: 42, q: true };
var { p, q } = o;

console.log(p); // 42
console.log(q); // true

var a, b;
({ a, b } = { a: 1, b: 2 });
  • 객체로부터 해체된 값이 undefined인 경우, 변수에 기본값을 할당할 수 있음
var { a = 10, b = 5 } = { a: 3 };

console.log(a); // 3
console.log(b); // 5
  • 새로운 변수명 할당과 기본값 할당을 한번에 할 수 있음
var { a: aa = 10, b: bb = 5 } = { a: 3 };

console.log(aa); // 3
console.log(bb); // 5

기본값 매개변수(default function parameter)

  • 기본값 함수 매개변수를 사용하면 값이 전달되지 않거나 undefined인 경우 명명된 매개변수를 기본값으로 초기화할 수 있음
  • JavaScript에서, 함수의 매개변수는 undefined가 기본
function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5, 2));
// Expected output: 10

console.log(multiply(5));
// Expected output: 5

multiply(5, 2); // 10
multiply(5); // 5
multiply(5, undefined); // 5
  • undefined로 전달해도 기본값으로 초기화 됨
  • 다른 타입이나 null은 불가능
function test(num = 1) {
  console.log(typeof num);
}

test(); // 'number' (num은 1로 설정됨)
test(undefined); // 'number' (num이 역시 1로 설정됨)

// 다른 falsy values로 테스트 하기
test(""); // 'string' (num은 ''로 설정됨)
test(null); // 'object' (num은 null로 설정됨)

arguments 객체

  • arguments 객체는 함수에 전달된 인수에 해당하는 Array 형태의 객체
  • 모든 함수 내에서 이용 가능한 지역 변수
function func1(a, b, c) {
  console.log(arguments[0]);
  // Expected output: 1

  console.log(arguments[1]);
  // Expected output: 2

  console.log(arguments[2]);
  // Expected output: 3
}

func1(1, 2, 3);
  • arguments 객체는 Array가 아님
  • Array와 비슷하지만, length 빼고는 어떤 Array 속성도 없음
  • Array로 변환은 가능
var args = Array.from(arguments);
var args = [...arguments];	// 전개 연산자 사용

전개 연산자

  • 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있음

...restParam(나머지 매개변수)

  • 나머지 매개변수 구문을 사용하면 함수가 정해지지 않은 수의 매개변수를 배열로 받을 수 있음
  • 마지막 매개변수만 나머지 매개변수로 설정할 수 있음
  • 함수의 마지막 매개변수 앞에 "..."를 붙이면 모든 후속 매개변수를 배열에 넣도록 지정
  • 함수 정의에는 하나의 ...만 존재할 수 있음
function sum(...theArgs) {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

console.log(sum(1, 2, 3));
// Expected output: 6

console.log(sum(1, 2, 3, 4));
// Expected output: 10
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");
// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five", "six"] <-- 배열임에 주목

myFun("one", "two", "three");
// a, "one"
// b, "two"
// manyMoreArgs, ["three"] <-- 요소가 하나지만 여전히 배열임

myFun("one", "two");
// a, "one"
// b, "two"
// manyMoreArgs, [] <-- 여전히 배열
  • arguments 객체는 실제 배열이 아님! 그러나 나머지 매개변수는 Array 인스턴스이므로 sort, map, forEach, pop 등의 메서드를 직접 적용할 수 있음
  • ...restParam은 후속 매개변수만 배열에 포함하므로 ...restParam 이전에 직접 정의한 매개변수는 포함하지 않음. 그러나 arguments 객체는, ...restParam의 각 항목까지 더해 모든 매개변수를 포함

화살표 함수

  • 일반 함수는 자신이 종속된 객체를 this로 가리키며, 화살표 함수는 자신이 종속된 인스턴스를 가리킴
  • 화살표 함수는 따로 { }를 열어 주지 않으면 연산한 값을 그대로 반환한다는 의미
profile
Record Everything!!

0개의 댓글