"A function is a piece of code that we can reuse over and over again in our code"
Function declarations vs. expressions
// function declarations
function calcAge1(birthYear) {
return 2021-birthYear;
}
const age1 = calcAge1(2000);
// function expressions
const calcAge2 = function(birthYear){
return 2021-birthYear;
}
const age2 = calcAge2(2000);
function expressions부분에서 익명함수 부분은 statement가 아니라 (당연히) expression이다 (expression produce a value).
calcAge2라는 변수에 function을 저장하는 꼴인데, 이는 즉 function은 Type이 아닌 Value라는 것을 알 수 있다.
Function declaration과 Function expressions의 가장 큰 차이점은 Function declaration의 경우 정의하기 전에 해당 함수를 부를 수 있다는 것이다.
"we can call function declarations before they are defined in the code"
// function declarations
const age1 = calcAge1(2000);
function calcAge1(birthYear) {
return 2021-birthYear;
}
이와 같이 선언하더라도 문제없이 작동한다. 하지만 function expressions의 경우 반드시 먼저 function을 정의한 후에 사용이 가능하다.
그럼 언제 function declaration과 function expression을 쓸까? 이건 각자의 성향, 취향에 따라 다르다.
해당 강좌의 강사의 경우는 function expression을 선호했는데, 그 이유는 function을 먼저 정의한 후에 해당 function을 부를 수 있기에 코드를 좀 더 좋은 구조로 짤 수 있고, 개인적으로 모든 값을 변수에 저장하는 것을 선호하기 때문이라 한다.
Arrow Function
Function expression을 좀 더 간결히 쓸 수 있는 function이며 ES6부터 추가되었다.
// function expressions
const calcAge2 = function(birthYear){
return 2021-birthYear;
}
// Arrow Function
const calcAge3 = birthYear => 2021-birthYear;
const age3 = calcAge3(2000);
위의 Arrow Function은 가장 기본형태이며 아래와 같이 {} 를 써서 정의할 수도 있다.
// multiple lines, multiple parameters
const calRetriement = (birthYear, firstName) => {
const age = 2021 - birthYear;
const ret = 65 - age;
return `${firstName} will retire in ${ret} years`;
}
'TIL > JAVASCRTIPT' 카테고리의 다른 글
Section2-20 Type Conversion and Coercion (0) | 2021.01.02 |
---|---|
Section2-13 let, const, var (0) | 2021.01.02 |
Section2-12 Data Type (0) | 2021.01.02 |