본문 바로가기

WEB개발

[펌]구글의 javascript 스타일 가이드

728x90
반응형

https://velog.io/@chayezo/%EA%B5%AC%EA%B8%80%EC%9D%98-javascript-%EC%8A%A4%ED%83%80%EC%9D%BC-%EA%B0%80%EC%9D%B4%EB%93%9C

 

구글의 javascript 스타일 가이드

13 Noteworthy Points from Google’s JavaScript Style Guidespace 2칸을 추천한다.세미콜론으로 마무리 해주자.Every statement must be terminated with a semicolon. 수평 정렬은 권장되

velog.io

Use spaces, not tabs

  • space 2칸을 추천한다.
// bad
function foo() {
  ∙∙∙∙let name;
}
// bad
function bar() {
  ∙let name;
}
// good
function baz() {
  ∙∙let name;
}

Semicolons ARE required

  • 세미콜론으로 마무리 해주자.

Every statement must be terminated with a semicolon.

// bad
let luke = {}
let leia = {}
[luke, leia].forEach(jedi => jedi.father = 'vader')

// good
let luke = {};
let leia = {};
[luke, leia].forEach((jedi) => {  
  jedi.father = 'vader';
});

Horizontal alignment is discouraged (but not forbidden)

  • 수평 정렬은 권장되지 않지만 금지되지는 않는다.

This practice is permitted, but it is generally discouraged by Google Style.

// bad
{
  tiny:   42,
  longer: 435, 
};
  
// good
{
  tiny: 42,
  longer: 435,
};

Don’t use var anymore

  • 모든 지역 변수를 const 또는 let으로 선언하자.
  • 변수를 재할당해야하는 경우가 아니라면 const를 사용하자.
  • var키워는 사용하지 않아야 한다.

Declare all local variables with either const or let.
Use const by default, unless a variable needs to be reassigned.
The var keyword must not be used.

// bad
var example = 42;

// good
let example = 42;

Arrow functions are preferred

  • 화살표 함수(=>)를 사용하자.
  • 화살표 함수는 더 간결하고 보기에 좋다.
  • 중첩된 함수의 경우 매우 유용하다.

Arrow functions provide a concise syntax and fix a number of difficulties with this.
Prefer arrow functions over the function keyword, particularly for nested functions

// bad
[1, 2, 3].map(function (x) {
  const y = x + 1;  
  return x * y;
});

// good
[1, 2, 3].map((x) => {
  const y = x + 1;  
  return x * y;
});

Use template strings instead of concatenation

  • 템플릿 리터럴을 사용하자.

Use template strings (delimited with `) over complex string concatenation, particularly if multiple string literals are involved.
Template strings may span multiple lines.

// bad
function sayHi(name) {
  return 'How are you, ' + name + '?';
}
// bad
function sayHi(name) {
  return ['How are you, ', name, '?'].join();
}
// bad
function sayHi(name) {
  return `How are you, ${ name }?`;
}

// good
function sayHi(name) {
  return `How are you, ${name}?`;
}

Don’t use line continuations for long strings

  • 일반 또는 템플릿 리터럴에서 줄 연속 (즉, 백 슬래시로 문자열 리터럴 내부의 줄 끝)을 사용하지 말자.
    ES5가 이것을 허용하더라도 슬래시 뒤에 후행 공백이 오면 까다로운 오류가 발생할 수 있다.
// bad (sorry, this doesn't show up well on mobile)
const longString = 'This is a very long string that \    
far exceeds the 80 column limit. It unfortunately \    
contains long stretches of spaces due to how the \    
continued lines are indented.';

// good
const longString = 'This is a very long string that ' +
      'far exceeds the 80 column limit. It does not contain ' +
      'long stretches of spaces since the concatenated ' + 
      'strings are cleaner.';

“for… of” is the preferred type of ‘for loop’

  • for ...in 루프는 객체에 더 좋고
  • for ...of 루프는 배열에 더 적합하다고 생각한다.

With ES6, the language now has three different kinds of for loops.
All may be used, though for-of loops should be preferred when possible.

let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);

for (let entry of iterable) {
  console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]

for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3

Don’t use eval()

  • eval 또는 Function(...string) 생성자를 사용하지 말자. (코드 로더 제외)
    이러한 기능은 잠재적으로 위험하며 단순히 CSP 환경에서 작동하지 않는다.

Do not use eval or the Function(...string) constructor (except for code loaders).
These features are potentially dangerous and simply do not work in CSP environments.

// bad
let obj = { a: 20, b: 30 };
let propName = getPropName();  // returns "a" or "b"
eval( 'var result = obj.' + propName );

// good
let obj = { a: 20, b: 30 };
let propName = getPropName();  // returns "a" or "b"
let result = obj[ propName ];  //  obj[ "a" ] is the same as obj.a

Constants should be named in ALL_UPPERCASE separated by underscores

  • 상수는 ALL_UPPERCASE(대문자 + 언더스코어)로만 명명한다.
    변수가 변경되지 않아야 한다고 확신하는 경우 상수 이름을 대문자로 표시하여 이를 나타낼 수 있다. 이렇게하면 코드 전체에서 사용되는 상수의 불변성이 분명해진다.
  • 상수가 함수 범위인 경우에 예외로 camelCase로 작성한다.

Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores.
A notable exception to this rule is if the constant is function-scoped.
In this case it should be written in camelCase.

// bad
const number = 5;
// good
const NUMBER = 5;

One variable per declaration

  • 모든 지역 변수 선언은 하나의 변수만 선언.

such as let a = 1, b = 2; are not used.

// bad
let a = 1, b = 2, c = 3;

// good
let a = 1;
let b = 2;
let c = 3;

Use single quotes, not double quotes

  • 큰 따옴표 대신 작은 따옴표 사용하기.
  • tip : 문자열에 작은 따옴표 문자가 포함되어 있으면 따옴표를 이스케이프 하지 않아도 되도록 템플릿 리터럴을 사용하자.
// bad
let directive = "No identification of self or mission."

// bad
let saying = 'Say it ain\u0027t so.';

// good
let directive = 'No identification of self or mission.';

// good
let saying = `Say it ain't so`;
728x90
반응형

'WEB개발' 카테고리의 다른 글

[JS] Geolocation API 사용하기  (1) 2023.10.04
Bootstrap + React, Bootstrap + Vue  (0) 2023.08.23
택배사 배송조회 링크  (0) 2022.12.02
Grid (Spread) 관련 각종 솔루선 정리  (0) 2022.12.02
스벨트(Svelte)의 특징  (0) 2022.11.30