JS/자바스크립트 Style Guide

14. Comparison Operators & Equality (JS style guide)

코비코 koreanvisionarycoder 2023. 2. 7. 09:09

==와 != 대신 ===와 !==를 사용한다. eslint: eqeqeq(===) (!==) > (==)


 

Conditional statements


  • if 와 같은 조건문 : ToBoolean 의 추상 메서드로 강제변환을 사용하여 식을 평가한다.
    식을 평가하는 규칙은 다음과 같다.
if ([0] && []) {
  // true
  // 배열은 객체이다. 빈객체도 객체임
  // 객체는 항상 true 
}
  • Objects -> true
  • Undefined -> false
  • Null -> false
  • Booleans -> true / false
  • Numbers
    • false : +0, -0, NaN
    • otherwise true
  • Strings
    • false : empty string ''
    • otherwise true

 

reference: boolean -> 축약 , 문자열/숫자 -> 명시적 비교


// bad
if (isValid === true) {
  // ...
}

// good
if (isValid) {
  // ...
}

// bad
if (name) {
  // ...
}

// good
if (name !== '') {
  // ...
}

// bad
if (collection.length) {
  // ...
}

// good
if (collection.length > 0) {
  // ...
}

 

Truth Equality and JavaScript by Angus Croll


 

어휘 선언이 있는 case/default 문 : { } braces 사용


  • Lexical declarations [어휘 선언]
  • let, const, function, and class
  • 스위치 블록 스코프가 존재한다.
  • case/default 에 { } 가 없다면 여러 case 절에서 동일한 것을 정의하려고 할 때 문제가 발생함.
// bad
switch (foo) {
  case 1:
    let x = 1;
    break;
  case 2:
    const y = 2;
    break;
  case 3:
    function f() {
      // ...
    }
    break;
  default:
    class C {}
}
switch (1) {
  case 1:
    let v ;
    break;
  case 2:
    let v;  // Uncaught SyntaxError: Identifier 'v' has already been declared
    break;
  case 3:
    function f() {
      // ...
    }
    break;
  default:
    class C {}
}
// good
switch (foo) {
  case 1: {
    let x = 1;
    break;
  }
  case 2: {
    const y = 2;
    break;
  }
  case 3: {
    function f() {
      // ...
    }
    break;
  }
  case 4:
    bar();
    break;
  default: {
    class C {}
  }
}

 

삼항의 중첩 X : 기본적으로 단일행 표현식


// bad
const foo = maybe1 > maybe2
  ? "bar"
  : value1 > value2 ? "baz" : null;

// split into 2 separated ternary(삼항) expressions
const maybeNull = value1 > value2 ? 'baz' : null;

// better
const foo = maybe1 > maybe2
  ? 'bar'
  : maybeNull;

// best

 

불필요한 삼항 표현식 X


// bad
const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? false : true;

// good
const foo = a || b;
const bar = !!c;
const baz = !c;

 

혼합 연산자 : () 로 감싸기


  • 혼합연산자는 우선순위가 모호하다.
    • +, -, ** 는 예외이다.
    • /, * 는 모호 하다.
// bad
const foo = a && b < 0 || c > 0 || d + 1 === 0;

// bad
const bar = a ** b - 5 % d;

// bad
// (a || b) && c 와 혼동될 수 있다.
if (a || b && c) {
  return d;
}

// bad
const bar = a + b / c * d;

// good
const foo = (a && b < 0) || c > 0 || (d + 1 === 0);

// good
const bar = a ** b - (5 % d);

// good
if (a || (b && c)) {
  return d;
}

// good
const bar = a + (b / c) * d;