JS _ 화살표함수(Arrow functions);

yoosg·2019년 12월 1일
0

화살표 함수는 ES6 문법으로 일반적인 function 키워드를 사용하는 함수보다 간결하게 표현이 가능한 함수이다.

//ES5
function() {}

//ES6
() => {}

소괄호만 남고 function키워드가 빠진채로 '=>'(arrow)가 추가된다.

1. 기본문법

//ES5
function getName() {}
const getName = function() {}

//ES6
const getName = () => {}	//변수에 저장되는 꼴로 표현된다.  

getName();  				//호출 방식은 같다.

2. 소괄호 생략

//ES5
const getName = function(name) {}

//ES6
const getName = (name) => {}		//인자가 하나일 때 소괄호 생략이 가능하다.
const getName = name => {}

//ES5
const getName = function(name, age) {}

//ES6
const getName = (name, age) => {}		//두개 이상은 불가능하다.

3. return 키워드 생략

//ES5
function getName(name) {
  return name;
}
getName('bar');	// bar

//ES6
const hi = name => { return name };	// return값 이외에 다른 실행문이 없으면 
const hi = name => name;			// return키워드와 {} 생략이 가능하다.
hi('bar');	// bar

// 하나만 생략하면 문제가 발생한다.
const hi = name => {name};			
hi('bar');  					// undefined
const hi = name => return name;	 // Error

const obj = () => ({a: 0, b: 1, c: 2});	//객체는 이렇게 표현 가능하다.
obj();	// {a: 0, b: 1, c: 2}

4. 콜백 표현

//ES5
let arr = [1, 2, 3, 4];
const squares = arr.map(function (x) { 
  return x * x;
});
squares  // [1, 4, 9, 16]

//ES6
const squares = arr.map(x => x * x);
squares  // [1, 4, 9, 16]

2개의 댓글

comment-user-thumbnail
2019년 12월 4일

화살표 함수가 헷갈렸었는데! 덕분에 개념 정리하고 가요!
다음 포스팅도 기대되어요^^

답글 달기
comment-user-thumbnail
2019년 12월 4일

arrow function 너무 어려워요ㅠㅠ
저도 arrow function 잘 못해서 정리했는데 제 벨로그도 찾아와 주세용
https://velog.io/@aaronddy/JavaScriptes6-arrow-function

답글 달기