[JS] 화살표 함수

soor.dev·2021년 4월 8일
0

Java Script

목록 보기
12/26
post-thumbnail

Arrow function?

ES6에서 도입된 function 키워드를 화살표로 축약해서 표시하는 방법이다.


1) 함수 표현식

const add = function(a, b) { 
  return a + b

2) 화살표 함수

const add = (a, b) => {
  return a + b
}

함수 본문에 return 문만 있는 경우는 return, {} 생략 가능

const add = (a, b) => a + b // working! ✅
const add = (a, b) => {a + b} // undefined 🚫
const add = (a, b) => (a + b) // working! ✅

함수 내 표현식이 두 줄 이상일 경우는 명시적으로 return, {} 쓰는 것이 좋음

const sum = arr => {
  return arr
  .filter(person => person.job === 'student')
  .reduce((sum, person) => (sum + person.grade), 0)
}

3) closure에서의 화살표 함수

함수 표현식

const add = function(a) {
  return function(b) {
    return a + b
  }
}
add(10)(20) // 3

화살표 함수 : function 키워드 제거

const add = (a) => {
  return (b) {
    return a + b
  }
}

화살표 함수 : function, 가장 안 쪽 return 제거

const add = a => {
  return b => a + b 
  // return 생략시에는 중괄호를 사용하지 않음
  // 파라미터가 하나라면 소괄호도 생략 가능
}

화살표 함수 : function, return 전부 제거

const add = a => b => a + b

0개의 댓글

관련 채용 정보