
화살표 함수는 함수 선언을 간결하게 표현할 수 있는 문법입니다. 특히 this 바인딩이 기존 함수와 다르게 동작해 콜백 함수나 클래스 메서드에서 유용하게 사용됩니다.
const 함수명 = (매개변수1, 매개변수2) => {
// 함수 내용
};
예시)
const add = (a, b) => a + b; // 한 줄로 바로 반환 가능
console.log(add(2, 3)); // 5
화살표 함수는 this를 상위 스코프에 바인딩합니다. 즉, 화살표 함수 내부의 this는 함수가 정의된 위치의 this를 가리킵니다.
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds); // Timer 객체의 seconds
}, 1000);
}
const timer = new Timer();
여기서 this는 Timer 객체를 가리킵니다. 전통적인 함수 표현식에서 this는 setInterval 내에서 글로벌 객체나 undefined를 가리킬 수 있기 때문에 화살표 함수로 작성하는 것이 안전합니다.
1) 기본 문법
템플릿 리터럴은 백틱(`)으로 감싸서 작성합니다. 변수나 표현식을 `${ }`로 감싸 삽입할 수 있습니다.
2) 여러 줄 문자열
const multiLine = `이것은 여러 줄로
작성된 텍스트입니다.
여기서 줄바꿈이 가능합니다.`;
console.log(multiLine);
3) 표현식 삽입
const a = 5;
const b = 10;
console.log(`a + b = ${a + b}`); // a + b = 15
1) 배열 구조 분해
const numbers = [1, 2, 3];
const [first, second, third] = numbers;
console.log(first, second, third); // 1 2 3
2) 객체 구조 분해
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 25
3) 중첩된 구조 분해
const person = { name: "Bob", address: { city: "New York", country: "USA" } };
const { address: { city, country } } = person;
console.log(city, country); // New York USA