arrow function

이용원·2022년 11월 14일
0

JAVASCRIPT

목록 보기
17/34

arrow function

간결한 function


// map에 arrow function을 사용
//map과 같은 메소드의 콜백함수들은 단 한번만 사용되며 재사용X
//그래서 arrow function 사용하면 편함

 // 기본적인 모양
 const square = (x) =>{
 return
}


// map에 arrow function을 사용
const number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

const numberDouble = number.map((item)=>{return item*2});

console.log(numberDouble)

const arrow = ()=>{
    console.log(this);
}
arrow();


//파라미터(인수)가 2개 이상일 때 () 반드시 필요
const add = (x, y)=>{
    return x+y;
}

//파라미터(인수)가 1개일 때 () 생략가능
const square2 = x =>{
    return x*x;
}

//파라미터(인수)가 0개일 때 ()생략 불가능
const rollDie =()=>{
    return Math.floor(Math.random()*6)+1;
}


return 생략

특정 상황에서 arrow function은 return 키워드를 생략할 수 있다.


const rollDie2 =()=>{
     Math.floor(Math.random()*6)+1;


}
console.log(rollDie2()); // undefined

//arrow function에서 return을 빼면 undefined가 나옴 
//arrow function이 단 하나의 값만 반환하는 경우
//중괄호 부분을 소괄호로 바꿔주면 자동적으로 리턴을 해준다.
const rollDie2 =()=>(Math.floor(Math.random()*6)+1)
console.log(rollDie2()); // 1~6 임의의 숫자 return


//이렇게 하나 이상의 일을 하게 되면 오류가 발생
const rollDie2 =()=>(Math.floor(
    let number = 0;
    Math.random()*6)+1
    )

//한줄로 쓰면 소괄호 생략 가능
const rollDie3 = () => Math.floor(Math.random() * 6) + 1;



//정규표현식 함수
const isEven1 = function (num) {
  return num % 2 === 0;
};

//기본적인 arrow function
const isEven2 = (num) => {
  return num % 2 === 0;
};

//매개변수 옆에 소괄호 없음
const isEven3 = num => {
  return num % 2 === 0;
};

//암시적인 리턴 (return 생략);
const isEven4 = num => (num % 2 === 0);

//매개변수와 return에 소괄호 생략

const isEven5 = num => num % 2 === 0;



//map에 arrow function 적용해보기

//function 키워드 사용
let movieName1 = movie.map(function(obj){
    return obj.name;
})

//기본적인 arrow function 사용
let movieName2 = movie.map((obj) => {return obj.name})

//{}를 ()를 바꿔서 암시적 리턴 사용으로 return 생략
let movieName3 = movie.map((obj) => (obj.name))

//()까지 생략
let movieName4 = movie.map(obj => obj.name);

console.log(movieName1); // [ 'heh1', 'heh2', 'heh3', 'heh4' ]
console.log(movieName2); // [ 'heh1', 'heh2', 'heh3', 'heh4' ]
console.log(movieName3); // [ 'heh1', 'heh2', 'heh3', 'heh4' ]
console.log(movieName4); // [ 'heh1', 'heh2', 'heh3', 'heh4' ]

0개의 댓글

관련 채용 정보