코딩/React 본 캠프

화살표함수, 조건(삼항)연산자, 단축평가

James Song 2024. 9. 20. 20:13
반응형

화살표함수

const add = function() {

      return a + b;

}

 

= const add = () => {

     return a + b; 

}

 

= const add = () => a + b;

return 이 한줄인 경우에는 중괄호와 return이 필요없다.

 

 조건연산자 = 삼항연산자

const score = 85;
const grade = score >= 80 ? "A" : "B";

? 앞에 조건을 붙히고 같거나 맞으면 "A" 를 다르거나 틀리면 "B" 

 

단축평가

  1. 논리합연산자 ( || )
    falsy
    falsy : false, 0, "", null, undefined, NaN

    const getUserName  = (user) => user.name || "신원미상"
  2. 논리곱연산자 ( && )
    truthy
    로그인 상태일 때 만 뿌려주고 싶을 때
  3. optional chaining
const user = {
     profile2: {
          name: "르탄이",
          details: {
                age: 30,
                 location: "서울시 강남구",
           },
      },
};

console.log(user.profile.details.age // (cannot read properties of undefined (reading 'details') 오류가 많이 난다.

console.log(user.profile?.details.age) // undefined (details 앞에 ? 를 써준다.

반응형