[Javascript] Airbnb javascript convention 중 새로알게된 점 정리

원문 바로가기

  • Function declarations are hoisted 링크
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // bad
    function foo() {
      // ...
    }
    
    // bad
    const foo = function () {
      // ...
    };
    
    // good
    // lexical name distinguished from the variable-referenced invocation(s)
    const short = function longUniqueMoreDescriptiveLexicalFoo() {
      // ...
    };
    
  • Put all imports aboue non-imoprt statements because imports are hoisted

  • Avoid using unary increments and decrements (++, --) 링크

  • 그냥 function은 hoisting되며 코드 이전에서 사용될 수 있지만, var에 assign되는 경우 variable name만 hoisting되며 function name, function body는 hoisting되지 않는다. 링크
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // the same is true when the function name
    // is the same as the variable name.
    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      var named = function named() {
        console.log('named');
      };
    }
    
    function example() {
      superPower(); // => Flying
    
      function superPower() {
        console.log('Flying');
      }
    }
    
  • Lexical declaration(let,const,function,and class)이 switch문의 case안에서 사용되는 경우 { }로 감싸주도록 한다 링크

  • Control statement가 너무 길어질 때:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // bad
    if (foo === 123
      && bar === 'abc') {
      thing1();
    }
    
    // bad
    if (
      foo === 123 &&
      bar === 'abc'
    ) {
      thing1();
    }
    
    // good
    if (
      foo === 123
      && bar === 'abc'
    ) {
      thing1();
    }