/ FRONTEND

클린코드 자바스크립트 4-4 분기 다루기(Default case 고려하기, Nullish coalescing operator, 드모르간 법칙)

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

분기 다루기 😎

Default case 고려하기👍

  • 기본값을 정해놓는다.
function sum(x, y) {
  x = x || 1;
  y = y || 1;
  return x + y;
}

sum();
function createElement(type, height, width) {
  const element = document.createElement(type || "div");
  element.style.height = height || 100;
  element.style.width = width || 100;

  return element;
}

createElement();

function registerDay(userInputDay) {
  switch (userInputDay) {
    case "월요일":
    case "화요일":
    case "수요일":
    case "목요일":
    case "금요일":
    case "토요일":
    case "일요일":
    default:
      throw Error("입력값이 유효하지 않습니다.");
  }
}

registerDay("월ㄹ요일");

parseInt(x, base);
// 안전하게 default 값을 넣어준다.
function safeParseInt(number, radix) {
  return parseInt(number, radix || 10);
}

safeParseInt(x);

Nullish coalescing operator👍

function createElement(type, height, width) {
  const element = document.createElement(type || "div");
  element.style.height = height || 100;
  element.style.width = width || 100;

  return element;
}

const el = createElement("div", 0, 0);

el.style.height; // 100px > 0은 falsy이므로 100 default 값
el.style.width; // 100px > 0은 falsy이므로 100 default 값

// null or undefined => ??
// falsy => ||
function createElement2(type, height, width) {
  const element = document.createElement(type || "div");
  element.style.height = height ?? 100;
  element.style.width = width ?? 100;

  return element;
}
const el2 = createElement("div", 0, 0);
el2.style.height; // 0px
el2.style.width; // 0px
function helloWorld(message) {
  if (!message) {
    return "Hello! World!";
  }

  return "Hello " + (message || "World");
}

// 에러 발생
console.log(helloWorld(0)); // Hello! World!
// 에러가 발생한다.
null || undefined ?? "foo" // JS가 오류를 방지하기 위해 만듬 Syntax error
(null || undefined) ?? "foo" // 이렇게 우선순위를 두어서 사용해야한다.

드모르간 법칙👍

무엇이 더 명시적인가?

  • 조건문 중 연산이 더 붙을 경우 드모르간 법칙을 사용할 수 있다.
  • true === not false
  • false === not true
const isValidUser = true; // 서버에서 가져온 데이터
const isValidToken = true; // 서버에서 가져온 데이터

if (isValidUser && isValidUser) {
  console.log("로그인 성공!");
}

if (!isValidUser || !isValidUser) {
  console.log("로그인 실패!");
}
if (A && B) {
  // 성공
}

if (!A || !B) {
  // 성공
}