공부 기록/Javascript
Functions - 고차 함수, 반환 함수, 팩토리 함수, 익명 함수
yurison
2023. 1. 18. 17:59
고차 함수
- 다른 함수와 함께 작동하거나 다른 함수에서 작동하는 함수 (Functions that operate on/with other functions.)
- They can accept other functions as arguments and return a function.
function callTwice(func) {
ㅤㅤfunc();
ㅤㅤfunc();
}
function rollDie() {
ㅤㅤconst roll = Math.floor(Math.random()*6)+1;
ㅤㅤconsole.log(roll);
}
callTwice(rollDie);
반환 함수
- 함수가 반환되는 함수
function makeMysteryFunc() {
ㅤㅤconst num = Math.random();
ㅤㅤif(num>0.5) {
ㅤㅤㅤㅤreturn function(){
ㅤㅤㅤㅤㅤㅤconsole.log("CONGRATS!");
ㅤㅤㅤㅤ}
ㅤㅤ} else {
ㅤㅤㅤㅤreturn function() {
ㅤㅤㅤㅤㅤㅤconsole.log("YOU LOSE");
ㅤㅤㅤㅤ}
ㅤㅤ}
}
팩토리 함수
- 함수를 만들어 주는 함수
function makeBetweenFunc(min, max) {
ㅤㅤreturn function(num) {
ㅤㅤㅤㅤreturn num >= min && num <= max;
ㅤㅤ}
}
const isChild = makeBetweenFunc(0, 18);
const isAdult = makeBetweenFunc(19, 64);
const isSenior = makeBetweenFunc(65, 120);
익명 함수
- 선언적 함수와의 차이점 : 익명 함수는 순차적으로 실행되므로, 함수 선언 전에 함수를 실행하는 경우 실행되지 않는다.
const square = function(num) {
ㅤㅤreturn num * num;
}