//ES5 function() {} //ES6 () => {}
이름이 없는 함수의 기본적인 표현이다. ES6에서는 function 이라는 키워드가 빠지고 소괄호만 남았다. 그리고 =>
(arrow)가 추가되었다.
//ES5 function getName() {} //ES6 const getName = () => {}
호출할 때는 둘 다 같다.
getName();
ES6는 함수를 getName 이라는 변수에 저장 했네요.
사실 function(함수)는 변수에 저장할 수 있는 하나의 식입니다.
그래서 ES5 일 때도 마찬가지로 변수에 저장할 수 있었습니다.
//ES5 //Function Declaration function getName() {} //ES5 //Function Expression const getName = function() {}
쓰임새가 다를 때가 있지만, 함수를 정의할 때는 일단 편한 방법으로 해주세요.
인자도 한 번 받아보겠습니다.
//ES5 const getName = function(name) {} //ES6 const getName = (name) => {} const getName = name => {}
//ES5 const getName = function(name, age) {} //ES6 const getName = (name, age) => {}
이제 return 하는 함수를 볼까요?
//ES5 function hi(text) { text += '하세요'; return text; } //ES6 const hi = text => { text += '하세요'; return text };
만약 함수가 실행내용이 딱히 없이 return
만 한다면 return
키워드와 중괄호가 생략가능합니다.
//ES5 function getName(name) { return name; } //ES6 const hi = name => { return name }; const hi = name => name;
헷갈리나요? 예제 하나만 더 보겠습니다.
//ES5 function getFullName(first, family) { return first + family; } //ES6 const hi = (first, family) => { return first + family }; const hi = (first, family) => first + family;
- function 키워드를 사용하여 표현된 welcome 함수를, 화살표 함수 표현으로 바꿔주세요.
function welcome(name){ return "안녕하세요" + name }
// 아래에서 변환해주세요! const hello = (name) => { return "안녕하세요" + name };
- 이후, 화살표 함수로 표현된 handleBio 함수를, function 키워드를 사용하여 표현된 함수로 바꿔주세요.
// ES6 const handleBio = (nickname, bio) => { const user = { nickname : nickname, bio : bio, } return user; }
// 아래에서 변환해주세요! function handleBio(nickname, bio) { const user = { nickname: nickname, bio: bio } return user }