화살표 함수(arrow function)를 정의할 때 사용되는 문법으로 간결하게 함수를 작성
(1)
function 함수이름() {
//어쩌구
}
(2)
var 함수이름 = function() {
//어쩌구
}
화살표 함수를 사용하면 이렇게 간단하게 만들 수 있다!
var 함수이름 = () => {
//어쩌구
}
const 함수이름 = (매개변수) => {
// 함수의 본문
return 값;
};
const add = (a, b) => {
return a + b;
};
console.log(add(2, 3)); // 출력: 5
const square = x => x * x;
console.log(square(4)); // 출력: 16
const add = (a, b) => a + b;
console.log(add(2, 3)); // 출력: 5
const greet = () => "Hello, World!";
console.log(greet()); // 출력: "Hello, World!"
function Person() {
this.age = 0;
// 화살표 함수: 상위 `this`를 사용
setInterval(() => {
this.age++; // Person의 `this`
console.log(this.age);
}, 1000);
}
new Person();
일반 function은 자신만의 this를 가지므로, 위 코드에서 일반 함수를 사용하면 this가 undefined가 되어 에러가 발생
function normalFunction() {
console.log(arguments); // [1, 2, 3]
}
const arrowFunction = () => {
console.log(arguments); // ReferenceError: arguments is not defined
};
normalFunction(1, 2, 3);
arrowFunction(1, 2, 3);