[Javascript] 함수의 종류
JS function types, function expression, IIFE, function declaration
정의
JavaScript 에서 함수를 정의하는 여러 방법.
1. Function Declaration (선언문)
function add(a, b) {
return a + b;
}
- 호이스팅 됨 (전체)
- 자기 이름으로 재귀 가능
- 일반 함수의
this동적
2. Function Expression (표현식)
const add = function(a, b) { return a + b; };
// named expression
const fact = function f(n) { return n <= 1 ? 1 : n * f(n-1); };
- 호이스팅 안 됨 (
const/let규칙) - named expression 의 이름은 함수 내부에서만 보임
- 콜백, 변수 할당에 자연스럽다
3. Arrow Function
const add = (a, b) => a + b;
const square = x => x ** 2;
const greet = () => 'hi';
const makePoint = (x, y) => ({ x, y }); // 객체는 괄호로
- 가장 짧은 문법
thislexical (정의 위치)arguments없음new불가- 자세히는 arrow function
4. IIFE (Immediately Invoked)
(function() {
// 즉시 실행, 스코프 격리
})();
(() => {
// 화살표 IIFE
})();
// 결과를 변수에
const result = (() => {
const x = compute();
return process(x);
})();
ES6 이전에는 모듈 / 스코프 격리에 자주 사용. 지금은 ES modules + 블록 스코프가 더 깔끔.
5. Method Shorthand
const obj = {
greet() { return 'hi'; }, // = greet: function() {...}
*gen() { yield 1; }, // generator method
async run() { await ... }, // async method
};
class Foo {
method() { ... } // class 안에서는 항상 method shorthand
}
6. Generator Function
function* gen() {
yield 1;
yield 2;
}
const it = gen();
it.next(); // { value: 1, done: false }
자세히는 JS Iterator / Generator.
7. Async Function
async function fetchData() {
const r = await fetch('/api');
return r.json();
}
const fn = async () => {
return await something();
};
자세히는 JS async/await.
8. Constructor Function (옛 OOP)
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() { return 'Hi ' + this.name; };
const p = new Person('Alice');
ES6 class 가 더 깔끔, 거의 모든 경우에 class 권장.
비교 표
| 특성 | declaration | expression | arrow |
|---|---|---|---|
| 호이스팅 | ✓ | ✗ | ✗ |
this | 동적 | 동적 | lexical |
arguments | ✓ | ✓ | ✗ (rest 사용) |
new | ✓ | ✓ | ✗ |
prototype | ✓ | ✓ | ✗ |
| 짧은 문법 | ✗ | ✗ | ✓ |
| 메서드로 적합 | ✓ | ✓ | ✗ |
| 콜백으로 적합 | △ | △ | ✓ |
매개변수
default
function greet(name = 'Guest') { ... }
rest
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
destructuring
function process({ name, age = 18 } = {}) { ... }
function point([x, y]) { ... }
arguments 객체
function foo() {
console.log(arguments); // 유사 배열 (array-like)
}
// arrow 함수에는 없음
const arr = () => arguments; // ❌
const arr2 = (...args) => args; // ✓
arguments 보다 ...rest 권장.
일급 함수 (First-class)
함수는 값으로 다룰 수 있다 (일급 함수).
const fns = [add, sub, mul]; // 배열 원소
const handler = chooseHandler(); // 반환값
button.onclick = handleClick; // 다른 함수에 전달
고차 함수 (Higher-order)
함수를 인자로 받거나 반환 (고차 함수).
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
함정
1. function declaration 의 호이스팅
foo(); // ✓ (호이스팅)
function foo() {}
bar(); // ❌ TypeError
var bar = function() {};
2. arrow vs 메서드
const obj = {
name: 'A',
greet: () => this.name, // ❌ this 는 외부 (보통 undefined)
greet2() { return this.name; } // ✓ 'A'
};
3. constructor 와 arrow
const Fn = () => {};
new Fn(); // ❌ TypeError
참고
이 글의 용어 (7개)
- [Javascript] Arrow Functionjavascript
- 정의 화살표 함수 (arrow function) 는 ES2015 (ES6) 에서 도입된 함수 표현식. 모양. 더 짧은 문법뿐 아니라 가 lexical 로 바인딩 되는 본질적 차이…
- [Javascript] async/awaitjavascript
- 정의 / 는 기반 비동기 코드를 마치 동기 코드처럼 쓸 수 있게 해주는 ES2017 의 문법 설탕. 본질은 Promise 그 자체, 문법만 다르다. 전체 동작 메커니즘은 글 참조…
- [Javascript] functionjavascript
- 정의 은 JavaScript 에서 함수를 만드는 가장 기본적인 키워드. 호이스팅, 동적 바인딩, 객체, 호출 등 과 구분되는 고유한 특성을 가진다. 함수가 값 으로 다뤄지는 의 …
- [Javascript] Iterator / Generatorjavascript
- 정의 - Iterator protocol : 메서드가 반환 - Iterable protocol : 가 iterator 반환 - Generator : 으로 정의, yield 로 값…
- [Javascript] this 바인딩javascript
- 정의 JavaScript 의 는 호출 방식에 따라 결정 되는 동적 바인딩. 4 가지 호출 방식 + arrow function (lexical) 규칙. 5 가지 규칙 | # | 규…
- 고차 함수javascript
- - 고차함수란 하나 이상의 함수를 인자로 받거나 반환하는 함수를 말합니다. - 일급 함수라는 특성을 활용해 실제로 함수를 다루는 연산을 수행하는 함수입니다. 즉, 아래 조건 중 …
- 일급 함수javascript
- - 함수를 값처럼 다루어 변수에 담거나 다른 함수의 인자로 전달하거나 함수의 반환값으로 사용할 수 있는 함수. 일급 함수의 이러한 특성을 활용하여 를 구현할 수 있습니다. - 함…
💬 댓글