함수 선언식(Function Declaration)은 미리 자바 스크립트의 실행 컨텍스트(execution context)에 로딩 되어 있으므로 언제든지 호출할 수 있다.
function f() {
// ...
};
함수 표현식(function expression)은 값이 될 수 있고, 함수 역시 값이 될 수 있다. 이는 함수를 선언하는 한 가지 방법일 뿐이며, 그 함수가 익명이 될 수도 있을 뿐이다. 함수 표현식은 식별자에 할당할 수도 있고 즉시 호출(IIFE)할 수도 있다.
함수 표현식은 함수 이름을 생략할 수 있다는 점을 제외하면 함수 선언과 문법적으로 완전히 같다.
const f = function() {
// ...
};
const f = () => {
// ...
};
(function() {
// IIFE body
})();
(() => {
// IIFE body
})()
// All the code is wrapped in the IIFE
(function () {
var private = "Private";
function init () {
start (private);
// code to start the application
}
function start () {
// ...
}
function end () {
// ...
}
init ();
}) ();
let isAdult;
(function init(age) {
let currentAge = age;
if (age >= 20) {
isAdult = true;
} else {
isAdult = false;
}
})(20);
console.log(isAdult); // true
console.log(currentAge); // Uncaught ReferenceError: currentAge is not defined
const Counter = (function counterIIFE() {
// 현재 counter 값을 저장하기 위한 변수
let current = 0;
return {
getCurrentValue: function () {
return current;
},
increaseValue: function () {
current = current + 1;
return current;
},
decreaseValue: function () {
current = current - 1;
return current;
},
};
})();
console.log(Counter.getCurrentValue()); // 0
console.log(Counter.increaseValue()); // 1
console.log(Counter.decreaseValue()); // 0