
함수명()과 같이 함수 내 로직을 실행할 수 있는데 이름 함수 호출이라고 한다. 참조 값으로 할당할 수 있다. 호출과 다르게 ()를 넣게 되면 함수 실행 출력 값이 할당이 되므로 함수를 참조하기 위해선 ()는 생략해야 한다. function declare(input) {
let output = input;
return output
}
/*함수 호출*/
declare('함수 선언')
// '함수 선언'
const expression = function(input) {
let output = input;
return output;
}
/*함수 호출*/
expression('함수 표현')
// '함수 표현'
function referFunc(input) {
let output = input;
return output
}
/***함수 참조***/
let variable = referFunc;
variable('referFunc 참조');
// 'referFunc 참조'
function keyword를 통한 함수 선언문은 변수 선언 var keyword 와 마찬가지로 hoisting이 발생해 호출 순서의 영향을 받지 않지만 함수 표현식은 호출 순서의 영향을 받는다.
declare('함수 선언 hoisting')
function declare(input) {
let output = input;
return output
}
// '함수 선언 hoistiong'
/*** Wrong way ***/
expression('can`t hoist') // '함수 표현'
const expression = function(input) {
let output = input;
return output;
}
// Uncaught ReferenceError: Cannot access 'expression' before initialization
/***Correct way***/
const expression = function(input) {
let output = input;
return output;
}
expression('Correct way!')
// 'Correct way!'
위 코드는 const를 통해 표현식을 구현했지만 let으로 선언해도 비슷한 Uncaught ReferenceError: expression is not defined error를 받으면서 표현식이 할당되지 않는다.
그럼 함수 표현식을 let, const가 아닌 변수 선언 시 hoisting var로 선언하면 어떻게 될까?
expression('Var keyword expression!')
var expression = function(input) {
let output = input;
return output;
}
// Uncaught TypeError: expression is not a function
변수 선언을 할때 hoisting이 발생하는 var keyword를 통해 함수 표현식을 구현해도 똑같이 function이 아니라는 error가 발생했다. var로 함수 표현식을 구현해도 역시 hoisting은 발생하지 않는다.
Closure
함수를 실행하기 전에 해당 함수에 인자를 넘기기 위해 사용할 수 있다.
Callback arguments
arguments로서 다른 함수의 인자 값으로 넘길 수 있다.
Reference
https://joshua1988.github.io/web-development/javascript/function-expressions-vs-declarations/
https://www.sitepoint.com/function-expressions-vs-declarations/