[JS] 함수 표현식, 고차 함수, 반환 함수

hye0n.gyu·2024년 7월 21일
0

JS

목록 보기
4/13
post-thumbnail

⭐ 함수 표현식

//함수 표현식의 형태
  var myFunction = function [name]([param1[, param2[, ..., paramN]]]) { statements }; 

//예시
const getRectArea = function (width, height) {
  return width * height;
};

✔ 함수 표현식과 함수 선언의 차이점

JavaScript에서함수 표현식함수 선언과는 달리 끌어올려지지 않는다.
함수 표현식은 정의하기 전에는 사용할 수 없다.

console.log(notHoisted); // undefined
//even the variable name is hoisted, the definition wasn't. so it's undefined.
notHoisted(); // TypeError: notHoisted is not a function

var notHoisted = function () {
  console.log("bar");
};

⭐ 고차 함수

고차 함수(Higher order function)는 함수를 인자로 전달받거나 함수를 결과로 반환하는 함수를 말한다.

function func(){
	console.log("func1")
}

function funcCallTwice(func){ //고차 함수
	func()
	func()
}

funcCallTwice(func)

⭐ 반환 함수

함수의 반환 값으로 함수 를 반환할 수 있다.

function getRectArea(width, height){ //고차 함수
	if(width*height>=400){
    	return function(){console.log("넓이 400 이상")}
    }else{
    	return function(){console.log("넓이 400 미만")}
    }
}

✔ 반환 함수의 활용

function makeBetweenArea(min, max){
	  return function(num){
        return num>=min&&num<=max
      }
}

const ex = makeBetweenArea(400,800)
let area = 30*20 //넓이
ex(area) //true

이렇게 재사용성이 높은 코드를 구현할 수 있게 된다.

profile
반려묘 하루 velog

0개의 댓글