자바스크립트에서 전통적으로 사용하는 함수 표현 방법
1. Function Declaration(함수 선언식)
const add = function(a, b) {
return a + b;
};
2. Function Expression(함수 표현식)
const add = (a, b) => {
return a + b;
};
화살표(=>)를 쓰인 함수는 Arrow Function 이라고 하고, ES6에서 새롭게 도입된 표기법
(a, b) => {
return a + b;
}
함수는 이름이 있는 함수와 이름이 없는 함수(Anonymous Function) 이 있는데
Anonymous Function의 경우는 주로 arrow를 쓰는 것을 권장한다.
ex)
step 1
const arr = [1, 2, 3, 4, 5];
function getSquare(x) {
return x * x;
}
const newArr = arr.map(getSquare);
console.log(newArr);
-----------------------------------------
step 2
// getSqure이란 함수를 사용하지 않고 map함수 인자로 넣어버림
(익명함수형태로!)
const arr = [1, 2, 3, 4, 5];
const newArr = arr.map(function(x){
return x*x;
});
console.log(newArr);
-----------------------------------------
step3
const arr = [1, 2, 3, 4, 5];
const newArr = arr.map((x) => {
return x*x;
});
console.log(newArr);