function 을 더욱 간결하고 아름답게 사용할수 있는 방법이다.
arrow function 을 이용하면 더욱 아름다운 코드를 만들 수 있다.
function getName(firstName){
reutrn firstName + "hong";
}
//기존에 function 을 정의하던 방법이다.
const getName = function(firstName){
reutrn firstName + "hong";
}
//const 를 활용하여 만든 function
const names = ["hello", "world", "good"];
const mappedNames = names.map(function(item){
return item + "1";
});
//map 내부에서 function 을 정의한 코드
function addNumber(item){
return item + "1";
}
const mappedNames = names.map(addNumber);
//function 을 따로 정의하여 호출한 코드
arrow (=>) 화살표를 이용하여 코드를 더 간결하게 사용해 보자.
const names = ["hello", "world", "good"];
const mappedNames = names.map((item,index)=>{
return item + "1";
});
//아래 더욱 간결하게
const mappedNames = names.map(item => item + "1");
function block 과 return 문구까지 삭제하였다.
이것을 implicit return 이라고 한다.
{ } 이 추가될 경우 implicit return 은 동작하지 않는다.
javascript 에는 this 라는 키워드가 있다.
이벤트 내의 function 에서 호출한 객체를 나타낸다.
const button = document.querySelector("button");
button.addEventListener("click", function(){
console.log(this);
this.style.backgroundColor = "red";
//this 는 버튼을 나타내는 키워드이다.
});
이제 위 코드를 arrow function 으로 바꿔보자
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log(this);
this.style.backgroundColor = "red";
//여기서의 this 는 window 객채를 가져온다.
//this.style 에서 오류가 발생하게 된다.
});
arrow function 내에서는 this 를 사용할 수 없다.
this 를 사용하려면 function 을 사용해야 한다.
const button = document.querySelector("button");
const handelClick = () =>{
console.log(this);
//역시 arrow function 이기 때문에 this 는 window 이다
}
button.addEventListener("click", handelClick);
const userObj ={
name : "gildong",
age : 24,
addYear = () => this.age++;
}
userObj.addYear();
userObj.addYear();
//addYear 역시 arrow function 이므로 내부의 this 는 window 를 나태낸다.
여러가지 사용 예시를 보자
=> find 함수
const emails = ["aaa@naver.com", "bbb@gmail.com", "ccc@hanmail.net"];
const foundMail = emails.find(item => item.includes("@gmail"));
//array 에서 find 함수에서 arrow function 을 사용했다.
//기존처럼 function 을 사용한다면 아래와 같이 복잡해진다.
const foundMail = emails.find(function(item){
return item.includes("@gmail");
});
=> filter 함수
const emails = ["aaa@naver.com", "bbb@gmail.com", "ccc@hanmail.net"];
const foundMail = emails.filter(item => !item.includes("@gmail"));
//@gmail 이 포함되지 않은 주소만 리턴된다.
=> forEach 함수
const emails = ["aaa@naver.com", "bbb@gmail.com", "ccc@hanmail.net"];
const cleand = [];
const foundMail = emails.forEach(item => cleand.push(item.split("@")[0]));
//@로 split 한 메일주소 앞부분만 리턴된다.
=> map 함수 (forEach 대신 사용 가능)
const emails = ["aaa@naver.com", "bbb@gmail.com", "ccc@hanmail.net"];
const foundMail = emails.map(item => item.split("@")[0]);
//map 함수를 사용해서 요소를 매핑한다.
const emails = ["aaa@naver.com", "bbb@gmail.com", "ccc@hanmail.net"];
const foundMail = emails.map((item, index) => ({
userName : item.split("@")[0],
index : index
}));
//{ } 이 추가되면 implicit return 이 동작하지 않지만 ()로 감싸게 되면
//object 를 리턴하는 implitcit return 을 의미한다.
함수에 전달하는 파라미터에 기본값을 지정할 수 있다.
arrow function 뿐만 아니고 기존 function 에서도 사용 가능하다.
function sayHi(aName){
return "Hello " + (aName || "gildong");
}
function sayHi(aName = "gildong"){
return "Hello " + aName;
}
Default Value 적용 시 간략하게 코드를 간략하게 사용 가능하다.
=> arrow function 에서의 사용
const sayHi = (aName = "gildong") => "Hello " + aName;
아래와 같이 상수로도 처리 가능하다.
const DefaultName = "gildong";
const sayHi = (aName = DefaultName) => "Hello " + aName;