arrow function 사용법 알아보기

Dl2l·2023년 1월 21일
0

Arrow Function

const favorite = ['cheesepizza','sashimi', 'sushi']

function addStar(item){
	return item + "⭐";
}
//function을 만들어 대입하는 방식은 혼란을 줄 수 있어 아래와 같은 방식으로 바뀌는 추세라고 한다!
const stars1 = favorite.map(addStar);

console.log(stars);

arrow function으로 function을 축약할 수 있다.


//arrow function 사용하기
const stars2 = favorite.map(addStar => {
	return item + "⭐";
});

//인자가 2개 이상일 경우 소괄호를 넣어준다.
const stars2 = favorite.map((addStar, index) => {
	return item + "⭐";
});

//implicit return : 표현식이 한 줄일 경우에는 return, 중괄호를 생략할 수 있다
const stars3 = favorite.map(addStar => item + "⭐");

arrow function을 사용하지 않아야 할 때

this를 사용할 때! arrow function을 쓰면 this가 window object를 바라보기 때문에
function()을 사용해줘야한다!


const button = document.quersSerlctor("button");

//이벤트 리스너를 붙이고 이벤트 리스너에 function이 있으면 
// js는 우리가 클릭한 버튼을 this 키워드에 넣는다.
button.addEventListner("click", function(){
  	this.style.backgroundColor = "red";
})

//////////////////////////////////////////////////////////
// arrow function 안에 this를 사용하면
// this를 window object로 가지고 있는다
button.addEventListner (){
  	this.style.backgroundColor = "red";
})

default vaulue

default값을 설정하지 않을 경우 인자에 값을 주지 않으면 함수 호출 시 undefined지만
deafult값을 설정해주면 인자가 없을 경우 default로 설정해준 값이 나온다.


//default 값이 없을 경우 함수 호출 시 undefined지만
//deafult 값을 설정해주면 값이 없을 경우 default로 설정해준 값이 나온다.

const test = (aaa ="default") => "hello " + aaa

console.log(test());
profile
안녕하세요

0개의 댓글

관련 채용 정보