티스토리 뷰

참조한 사이트
https://ui.toast.com/fe-guide/ko_CODING-CONVENTION
https://github.com/airbnb/javascript#variables--unary-increment-decrement

새로 알게 된 점

지역 변수 및 private 변수명은 '_'로 시작한다.

let _privateVariableName;
let _privateFunctionName;

// 객체일 경우
const customObjectName = {};
customObjectName.propertyName;
customObjectName._privatePropertyName;
_privateCustomObjectName;
_privateCustomObjectName._privatePropertyName;

 

URL, HTML 같은 범용적인 대문자 약어는 대문자 그대로 사용한다.

parseHTML
parseXML

 

외부 모듈과 내부 모듈을 구분하여 사용한다.

// 선언 사이 공백을 두면 가독성이 좋아진다.
const lodash = require('lodash');
const $ = require(jquery);
const handlebars = require('handlebars');
const d3 = require('d3');

const pluginFactory from '../../factories/pluginFactory';
const predicate from '../../helpers/predicate';
const raphaelRenderUtil from '../../plugins/raphaelRenderUtil';

 

객체의 프로퍼티가 1개인 경우에만 한 줄 정의를 허용하며, 2개 이상일 경우에는 개행을 강제한다.

// Bad - 개행
const obj = {foo: 'a', bar: 'b'}

// Good
const obj = {foo: 'a'};

// Good
const obj = {
  foo: 'a'
};

 

즉시 실행 함수는 권장되는 패턴으로만 사용한다.

// Bad
(function() {
  ...
})();

// Good
(function() {
  ...
}());

 

화살표 함수의 파라미터가 하나이면 괄호를 생략한다.

화살표 함수의 이점을 최대한 살릴 수 있다.

 

암시적 반환을 최대한 활용한다.

// Bad
[1, 2, 3].map(number => {
  const nextNumber = number + 1;
  `A string containing the ${nextNumber}.`;
});

// Good - 암시적 return을 사용
[1, 2, 3].map(number => `A string containing the ${number + 1}.`);

 

switch-case 사용 시 각 구문은 break, return, throw 중 한 개로 끝나야 하며 default문이 없으면 // no default 표시를 해준다.

  // Good - 여러 케이스가 하나의 처리를 할 때는 break생략 허용
  switch (value) {
    case 1:
    case 2:
      doSomething();
      break;

    case 3:
      return true;

    // no default
  }

 

Object.prototype 메소드를 바로 호출하지 않는다

  // bad
  console.log(object.hasOwnProperty(key));

  // good
  console.log(Object.prototype.hasOwnProperty.call(object, key));

  // best
  const has = Object.prototype.hasOwnProperty;
  console.log(has.call(object, key));

 

Object.assign 메소드로 Object를 복사할 시 스프레드 연산자를 사용한다.

Object는 얕은 복사를 하기 때문. 마찬가지로 배열 복사 시에도 스프레드 연산자를 사용한다.

  // very bad
  const original = { a: 1, b: 2 };
  const copy = Object.assign(original, { c: 3 }); 
  delete copy.a;

  // good
  const original = { a: 1, b: 2 };
  const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }

  const { a, ...noA } = copy; // noA => { b: 2, c: 3 }

 

유사배열 객체를 배열로 바꾸기 위해 Array.from을 사용한다.

유사 배열 객체란?

객체처럼 선언하나 객체의 개수에 대한 정보값 length 를 가지고 있는 객체. key 값은 인덱스처럼 0부터 시작하여 1씩 증가해야 한다.

   const arrLikeObject = {
     0: 'hello',
     1: 'world',
     2: 'It's me',
     length: 3
   }

Array.from 사용 예시

     const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };

  // bad
  const arr = Array.prototype.slice.call(arrLike);

  // good
  const arr = Array.from(arrLike);

 

배열을 스프레드 복사 후 map 함수를 사용하기 보다 Array.from을 사용한다.

  // bad
  const baz = [...foo].map(bar);

  // good
  const baz = Array.from(foo, bar);

 

배열 전용 콜백 함수에선 return을 사용한다.

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

  // good
  [1, 2, 3].map((x) => x + 1);

  // bad
  inbox.filter((msg) => {
    const { subject, author } = msg;
    if (subject === 'Mockingbird') {
      return author === 'Harper Lee';
    } else {
      return false;
    }
  });

  // good
  inbox.filter((msg) => {
    const { subject, author } = msg;
    if (subject === 'Mockingbird') {
      return author === 'Harper Lee';
    }

    return false;
  });

 

복수의 프로퍼티를 가져와 선언할 때 선호되는 형식은 다음과 같다.

  // bad
  function getFullName(user) {
    const firstName = user.firstName;
    const lastName = user.lastName;

    return `${firstName} ${lastName}`;
  }

  // good
  function getFullName(user) {
    const { firstName, lastName } = user;
    return `${firstName} ${lastName}`;
  }

  // best
  function getFullName({ firstName, lastName }) {
    return `${firstName} ${lastName}`;
  }
  const arr = [1, 2, 3, 4];

  // bad
  const first = arr[0];
  const second = arr[1];

  // good
  const [first, second] = arr;

 

여러개의 값을 반환해야 할 때, Array보단 Object 형식으로 반환한다.

  // bad
  function processInput(input) {

    return [left, right, top, bottom];
  }
  // good
  function processInput(input) {

    return { left, right, top, bottom };
  }

 

100자를 초과하는 문자열도 한 줄에 쓴다.

  // bad
  const errorMessage = 'This is a super long error that was thrown because \
  of Batman. When you stop to think about how Batman had anything to do \
  with this, you would get nowhere \
  fast.';

  // bad
  const errorMessage = 'This is a super long error that was thrown because ' +
    'of Batman. When you stop to think about how Batman had anything to do ' +
    'with this, you would get nowhere fast.';

  // good
  const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';

 

함수 선언식 보다 함수 표현식을 사용한다.

  // bad
  function foo() {
    // ...
  }

  // bad
  const foo = function () {
    // ...
  };

  // good
  // lexical name distinguished from the variable-referenced invocation(s)
  const short = function longUniqueMoreDescriptiveLexicalFoo() {
    // ...
  };

 

default 값이 있는 파라미터는 뒤에 작성한다.

  // bad
  function handleThings(opts = {}, name) {
    // ...
  }

  // good
  function handleThings(name, opts = {}) {
    // ...
  }

 

function을 선언관련

  // bad
  const f = function() {}
  const g = function (){}

  // good
  const x = function () {}

  // bad
  function test(){
    console.log('test');
  }

  // good
  function test() {
    console.log('test');
  }

  // bad
  function fight () {
    console.log ('Swooosh!');
  }

  // good
  function fight() {
    console.log('Swooosh!');
  }

 

파라미터를 의미없이 재할당하지 않는다.

  // bad
  function f1(a) {
    a = 1;
    // ...
  }

  function f2(a) {
    if (!a) { a = 1; }
    // ...
  }

  // good
  function f3(a) {
    const b = a || 1;
    // ...
  }

  function f4(a = 1) {
    // ...
  }

 

boolean 연산 관련

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

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

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

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

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

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

 

주석 스타일

  • 주석은 옆에 쓰기보다는 위에 쓴다.
  • 주석 위는 한 칸 띄워준다.
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함