/ FRONTEND

클린코드 자바스크립트 4-2 분기 다루기(truthy & falsy, 단락 회로 평가)

Clean Code JS 강좌는 여러 절로 구성되어 있습니다.

분기 다루기 😎

truthy & falsy👍

if ("string".length) {
}

if (10) {
}

if (boolean) {
}
// truthy
true;
{
}
[];
42;
("0");
("false");
new Date();
3.14 - 3.14;
Infinity - Infinity;
// falsy
false;
null;
undefined;
0;
0n;
NaN;
("");

단락 회로 평가👍

true && true && "도달O";
true && false && "도달X";

false || false || "도달O";
false || true || "도달X";
function fetchDate() {
  if (state.data) {
    return state.data;
  } else {
    return "Fetching....";
  }
}

return state.data ? state.data : "Fetching..."; // 삼항 연산자 이용
return state.data || "Fetching..."; // 단락회로 평가 이용

// 안 좋은 예
function favoriteDog(someDog) {
  let favoriteDog;
  if(someDog) {
    favoditeDog = someDog;
  } else {
    favoriteDog='냐옹'
  }
  return favoriteDog;
})

// 좋은 예
function favoriteDog(someDog) {
  return someDog||'냐옹';
}

favoriteDog() // => 냐옹
favoriteDog('뽀삐') // => 뽀삐
// 안 좋은 예
const getActiveUserName = (user, isLogin) {
  if(isLogin) {
    if(user){
      is(user.name){
        return user.name;
      } else {
        return '이름없음';
      }
    }
  }
}

// 좋은 예
const getActiveUserName = (user, isLogin) {
  if(isLogin && user) {
    if(user.name) {
      return user.name;
    } else {
      return '이름없음';
    }
  }
}

// 더 좋은 예
const getActiveUserName = (user, isLogin) {
  if(isLogin && user) {
    return user.name || '이름없음
  }