프론트엔드 개발/Javascript

자바스크립트 - 코딩 컨벤션

snowman95 2021. 8. 28. 15:15
728x90
반응형

 

 

이 게시물은 구글 자바스크립트 스타일 가이드를 따른다.

 

Google JavaScript Style Guide

Google JavaScript Style Guide 1 Introduction This document serves as the complete definition of Google’s coding standards for source code in the JavaScript programming language. A JavaScript source file is described as being in Google Style if and only i

google.github.io

 

  1. 코드는 Tab 대신 Space 2칸 들여쓰기 권장
    if (...) {
      something...
    }
  2. var 사용 금지, 기본적으로 const로 선언하고, 변하는 값을 let으로 변경하는 습관을 가지자.
    var num1 = 2    // Bad
    let num3 = 2;   // Good (변하는 값)
    const num2 = 2; // Good (변하지 않는 값)
  3. 세미콜론으로 문장을 끝낸다.
    const num1 = 2  // Bad
    const num2 = 2; // Good
  4. 연산자, 값 사이에 공백을 넣는다.
    const num=2;   // Bad
    const num = 2; // Good
  5. 식별자 유형별 규칙
    1) 패키지는 lowerCamelCase
    2) 클래스는 UpperCamelCase
    3) 메소드는 lowerCamelCase
    4) 열거형은 UpperCamelCase
    5) 상수는 밑줄로 구분된 대문자 CONSTANT_CASE
    6) 상수 아닌 필드이름/지역변수/매개변수/ lowerCamelCase
    7) 함수는 lowerCamelCase

    lowerCamelCase = 첫글자를 소문자로 시작해서 뒤에 오는 단어들의 첫글자를 대문자로 표기
    UpperCamelCase= 첫글자를 대문자로 시작해서 뒤에 오는 단어들의 첫글자를 대문자로 표기
    const camelCase = "OK"          // Good
    const not_cammel_Case = "notOK" // Bad
     
  6. 한 줄에 하나의 변수만 선언
    const num1 = 1, num2 = 2   // Bad
    const num3 = 1;            // Good
  7. 배열/객체 요소마다 쉼표 추가
    const arr = [    // Good
      123,
      456,
      789,
    ];
    
    const object = [ // Good
      name:'bob',
      age:123,
    ];
  8. 모든 제어 구문에 중괄호 사용
    if (someVeryLongCondition())  // Bad
      doSomething();
    if (someVeryLongCondition()){ // Good
      doSomething();
    }
    
    for (let i = 0; i < foo.length; i++) bar(foo[i]); // Bad
    for (let i = 0; i < foo.length; i++){             // Good
      bar(foo[i]);
    }
    
    ※ 예외 : 줄 바꿈 없이 한 줄에 완전히 들어갈 수 있는 간단한 if 문(else 없음)
    if (shortCondition()) foo();​
  9. 반복문은 가능하면 for of 문 사용을 권장

  10. 비교는 === 또는 !=== 을 사용
    if (a === b) {
      ...
    }
  11. 템플릿 문자열 사용
    function Hello(name) {   // Bad
      return "Hello" + "name";
    }
    
    function Hello(name) {   // Good
      return `Hello ${name}`;
    }​
  12. 화살표 함수 사용
    var arr1 = [1, 2, 3];
    var pow1 = arr.map(function (x) { // ES5 Not Good
      return x * x;
    });
    
    const arr2 = [1, 2, 3];
    const pow2 = arr.map(x => x * x); // ES6 Good

 

반응형