주의) 1개의 강좌안에서 First-class Function부분만 따로 빼냄_
First-class function
- Functions are treated like any oter variable
1) can be assigned as value to variable ; 변수에 할당가능
2) can be passed as an argument to otehr functions. ; 인자값으로 전달 가능.
3) can be returned by another function. ; return 값으로 return 된다.
- Function expression
a function declaration can be called earlier than it is defined. (hoisted) ;
a function expression is created when the excution reaches it.
const print = function(){ // 함수에 이름이 없이 ( anonymous function ; 익명함수), 필요한 부분만 작성하여 변수에 할당함
console.log('print');
};
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1,3));
- Callback function using function expression
: 함수 안에서 다른 함수를 call한다.
01) anonymous function ; 익명함수
const printYes = function() {
console.log('yes!');
};
02) named function
better debugging in debugger's stack traces
const printNo = function print() {
console.log('no@!!');
//print();
// recursions ; 피보나치수열, 반복되는 평균값 등 사용시에만 무한대로 호출.
};
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo) ;
3 Arrow Function
- 화살표 함수는 ES6문법이다. function 키워드 사용해서 함수를 만든 것보다 간단히 함수를 표현할 수 있다.
- 항상 익명함수로 선언한다.
- 함수의 수행로직이 길경우 코드블록{}안에 넣어줄수 있다. 이때, 반드시
return 키워드를 넣어줘야한다!
const simplePrint = function(){
console.log('simplePrint!');
};
const simplePrint_2 = () => console.log('simplePrint!_2'); // Arrow Function
const add = (a, b) => a+b; // Arrow Function
const add_2 = (a,b){ // Arrow Function , 함수의 실행로직이 많을시 {코드블록}안에 넣어줌,
return a*b; // 이때, 반드시 retrun 키워드를 줘야함!!
}
04) IIFE : Immediately Invoked Function Expression ; 선언함과 동시에 호출함! => function declare자체를 (괄호)로 묶어줌!!
(function hello() {
console.log('IIFE');
})