함수의 표현
First-class function
functions are treated like any other variable can be assigned as a value to variable : 함수는 다른 변수와 마찬가지로 변수에 할당이 됨
can be passed as an argument to other functions : 함수에 parameter로 전달이 됨
can be returned by another function : 함수를 return값으로도 return이 됨
1. 함수 표현식 (Function Expression)
a function declaration can be called earlier than it is defined (hoisted) : 함수가 선언되기 전에도 먼저 호출 가능, 자바스크립트 엔진이 선언된 것을 제일 위로 올려주기 때문
a function expression is created when the execution reaches it
함수 표현식에서는 함수명을 생략할 수 있음 → 익명함수 사용
function sum(a, b) {
return a + b;
}
const print = function () { // anonymous function(익명 함수)
console.log("print");
};
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1, 3));
2. 콜백 함수 (Callback Function using function expression)
함수를 전달해서 조건이 맞을 때 호출할 수 있는 함수
파라미터로 함수를 전달받아 함수의 내부에서 실행하는 함수 다른 함수에 매개변수로 넘겨준 함수
function randomQuiz(answer, printYes, printNo) {
if (answer === "love you") {
printYes();
} else {
printNo();
}
}
// anonymous function
const printYes = function () {
console.log("yes!");
};
// named function
// better debugging in debugger's stack traces
// recursions
const printNo = function print() {
console.log("no!");
// print(); // recursions : 함수 안에서 함수 자신을 호출하는 것으로 이 예시처럼 쓰면 무한 로딩.
};
randomQuiz("wrong", printYes, printNo); //no!
randomQuiz("love you", printYes, printNo); //yes!
3. 화살표 함수 (Arrow Function)
function 키워드 대신 화살표( => )를 사용하여 간략한 방법으로 함수를 선언 할 수 있음
// const simplePrint = function () {
// console.log('simplePrint!');
// };
const simplePrint = () => console.log("simplePrint!");
const add = (a, b) => a + b;
const simpleMultiply = (a, b) => {
// do something more
return a * b;
};
simplePrint();
4. IIFE (Immediately Invoked Function Expression)
함수를 선언함과 동시에 호출, 자바스크립트에서 함수를 바로 실행하고 싶을 때 사용
(function hello() {
console.log("IIFE");
})();
Quiz! Function Calculate
// Fun qiuz time💖
// function calculate(command, a, b)
// command: add, substract, divide, multiply, remainder
function calculate(command, a, b) {
switch (command) {
case 'add':
return a + b;
case 'substract':
return a - b;
case 'divide':
return a / b;
case 'multiply':
return a * b;
case 'remainder':
return a % b;
default:
throw Error('unknown command')
}
}
console.log(calculate('add', 2, 3));
Last updated
Was this helpful?