🏹
함수형 · ES6
중급 · 선수: 09_구조분해와_스프레드
10. 화살표 함수
본문이 여러 줄이면 중괄호와 `return` 을 명시합니다.
화살표 함수this간결한 표기
소요 시간
⏱ 약 1시간
난이도
📊 중급
선수 조건
🎯 단원 9
결과물
본문이 여러 줄이면 중괄호와 `return` 을 명시합니다.
이 강의에서 배우는 것
- 1화살표 함수의 문법을 안다.
- 2본문이 한 줄인 경우 암묵 반환(implicit return) 을 활용한다.
- 3`function` 과 화살표의 `this` 차이를 설명할 수 있다.
- 4콜백으로 화살표 함수를 자연스럽게 사용한다.
- 5화살표 함수가 적절하지 않은 경우(메서드, 생성자)를 안다.
소개
본문이 여러 줄이면 중괄호와 `return` 을 명시합니다.
핵심 개념
1. 기본 문법
javascript
const add = (a, b) => a + b;
const square = x => x * x; // 매개변수 1개면 괄호 생략 가능
const log = () => console.log("hi"); // 인자 없음 → 빈 괄호본문이 여러 줄이면 중괄호와 `return` 을 명시합니다.
javascript
const greet = (name) => {
const msg = `안녕, ${name}`;
return msg;
};2. 객체를 암묵 반환
객체 리터럴은 함수 본문 블록과 모양이 같아서 괄호로 감싸야 합니다.
javascript
const make = (x, y) => ({ x, y });3. this 차이
일반 `function` 의 `this` 는 호출 방식에 따라 결정되지만, 화살표 함수는 **선언된 위치의 this** 를 그대로 사용합니다 (lexical this).
javascript
const obj = {
name: "A",
hello1: function () { return this.name; },
hello2: () => this?.name,
};
obj.hello1(); // "A"
obj.hello2(); // undefined (선언 시점의 this)따라서 객체의 메서드는 보통 `function` 이나 단축 메서드 문법을 쓰고, 콜백처럼 외부 this 를 유지하고 싶을 때는 화살표를 씁니다.
4. 콜백에 적합
javascript
[1, 2, 3].map((x) => x * 10); // [10, 20, 30]
setTimeout(() => console.log("done"), 100);핵심 예제
| 파일 | 다루는 내용 |
|---|---|
| `01_basic.js` | 기본 문법, 매개변수 형태 |
| `02_implicit_return.js` | 암묵 반환, 객체 반환 |
| `03_this_diff.js` | this 차이 비교 |
| `04_callbacks.js` | 배열 메서드 콜백 |
src/01_basic.js
javascript
/**
* 화살표 함수 기본 문법
*/
"use strict";
const add = (a, b) => a + b;
const square = (x) => x * x;
const noArg = () => 42;
console.log(add(2, 3));
console.log(square(5));
console.log(noArg());
const greet = (name) => {
const msg = `Hi, ${name}`;
return msg;
};
console.log(greet("Sun"));
src/02_implicit_return.js
javascript
/**
* 암묵 반환과 객체 반환
*/
"use strict";
const double = (x) => x * 2;
console.log(double(7));
// 객체 반환은 괄호 필수
const point = (x, y) => ({ x, y });
console.log(point(1, 2));
// 잘못된 예 (블록으로 해석)
const wrong = (x, y) => { x, y };
console.log("wrong =", wrong(1, 2)); // undefined
src/03_this_diff.js
javascript
/**
* this 차이
*/
"use strict";
const obj = {
name: "ObjA",
fn() {
return this.name;
},
arrow: () => {
// lexical this = 모듈/전역
return typeof this === "undefined" ? "undefined" : "global";
},
};
console.log("fn =", obj.fn());
console.log("arrow =", obj.arrow());
// 콜백에서 외부 this 유지가 필요한 경우 화살표가 유리
const timer = {
seconds: 0,
start() {
const tick = () => {
this.seconds += 1;
};
tick();
tick();
return this.seconds;
},
};
console.log("timer =", timer.start()); // 2
src/04_callbacks.js
javascript
/**
* 배열 콜백으로서 화살표 함수
*/
"use strict";
const nums = [1, 2, 3, 4, 5];
console.log(nums.map((x) => x * x));
console.log(nums.filter((x) => x % 2 === 0));
console.log(nums.reduce((a, b) => a + b, 0));
setTimeout(() => console.log("delayed log"), 10);
자주 하는 실수
- 객체 반환 시 괄호를 빼서 블록으로 해석되어 `undefined` 반환.
- 화살표 함수를 객체 메서드로 정의하고 `this` 가 없다고 당황.
- 화살표 함수는 `arguments` 객체가 없다는 점을 잊는다.
- 화살표 함수는 생성자(`new`) 로 호출할 수 없다.
- 한 줄 함수에 `return` 까지 적어 SyntaxError.
FAQ
Q1. 화살표 함수를 항상 써도 되나요?
메서드와 프로토타입 정의는 `function` 이 더 적합합니다.
Q2. arguments 가 필요하면?
rest 매개변수(`...args`) 를 쓰세요.
Q3. 익명 함수와 차이는?
화살표도 익명이며, 변수에 할당해 이름을 부여합니다. 다만 `name` 속성은 변수명으로 추론됩니다.
과제
- `homework_01.js` — `function` 으로 짠 코드를 화살표로 변환하세요.
- `homework_02.js` — 객체 반환 화살표 함수로 좌표 생성기를 만드세요.
homework/README.md
## homework_01.js 아래 함수들을 화살표 함수로 바꾸세요.
javascript
function add(a, b) { return a + b; }
function isEven(n) { return n % 2 === 0; }
function shout(msg) { return msg.toUpperCase() + "!"; }## homework_02.js `makePoint(x, y)` 를 화살표 함수로 작성해 `{ x, y, distance }` 객체를 반환하세요. `distance` 는 원점에서의 거리.
homework/answer/homework_01.js
javascript
/**
* 과제 1: 화살표로 변환
*/
"use strict";
const add = (a, b) => a + b;
const isEven = (n) => n % 2 === 0;
const shout = (msg) => msg.toUpperCase() + "!";
console.log(add(2, 3));
console.log(isEven(4));
console.log(shout("hello"));
homework/answer/homework_02.js
javascript
/**
* 과제 2: 좌표 생성기
*/
"use strict";
const makePoint = (x, y) => ({
x,
y,
distance: Math.hypot(x, y),
});
console.log(makePoint(3, 4)); // { x:3, y:4, distance:5 }
다음 단원
[11_배열_고차함수](../11_배열_고차함수/) — map/filter/reduce.