12. Variables (JS style guide)

코비코 koreanvisionarycoder ㅣ 2023. 1. 26. 09:59

변수 선언 은 항상 const let eslint: no-undef prefer-const


Always use const to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.

  • 전역 변수가 생성되지 않는다.
  • 전역 변수 공간을 어지럽히지 않는다.
// bad
superPower = new SuperPower();

// good
const superPower = new SuperPower();

하나의 변수 선언/할당 : 하나의 const let eslint: one-var


Use one const declaration per variable.

  • 새로 변수를 선언하고 추가할 때 더 쉽다.
  • 하나의 const/let 에 여러 변수를 나열하면, ; 와 , 을 고려해야 한다.
  • 디버그를 할 때, 한줄로 쓰면 한번에 뛰어넘는다.
    • 단계별로 관찰 할 수 없다.
// bad
const items = getItems(),
    goSportsTeam = true,
    dragonball = 'z';

// bad
// (compare to above, and try to spot the mistake)
const items = getItems(),
    goSportsTeam = true;
    dragonball = 'z';

// good
const items = getItems();
const goSportsTeam = true;
const dragonball = 'z';

const/ let 의 그룹화


Group all your consts and then group all your lets.

  • 그룹화는, const 를 그룹화하고 다음에 let 을 그룹화 해준다. 왜? 이전에 할당한 변수에 대해 나중에 새 변수를 추가하는 경우에 유용하기 때문이다.

.

// bad
let i, len, dragonball,
    items = getItems(),
    goSportsTeam = true;

// bad
let i;
const items = getItems();
let dragonball;
const goSportsTeam = true;
let len;

// good
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;

합리적인 위치에 변수할당문 사용


Assign variables where you need them, but place them in a reasonable place.

  • 필요한 위치 근처에 둔다.
  • let/const 은 block 스코프 이기 때문이다.
// bad - unnecessary function call
function checkName(hasName) {
  const name = getName();

  if (hasName === 'test') {
    return false;
  }

  if (name === 'test') {
    this.setName('');
    return false;
  }

  return name;
}

// good
function checkName(hasName) {
  if (hasName === 'test') {
    return false;
  }

  const name = getName();

  if (name === 'test') {
    this.setName('');
    return false;
  }

  return name;
}

변수 할당문의 체이닝 X eslint: no-multi-assign


  • 변수 할당문의 체이닝은 암묵적으로 글로벌 변수를 만들어 낸다.
// bad
(function example() {
  let a = b = c = 1;
  // let a = ( b = ( c = 1 ) );
  // let 은 a 에게만 적용된다. 
  // b 와 c 는 전역 변수가 된다.
}());

console.log(a); // throws ReferenceError
console.log(b); // 1
console.log(c); // 1

// good
(function example() {
  let a = 1;
  let b = a;
  let c = a;
}());

console.log(a); // throws ReferenceError
console.log(b); // throws ReferenceError
console.log(c); // throws ReferenceError

//  `const` 도 마찬가지.

단항 증감 (++, --) X eslint no-plusplus


  • 단항 증감은 세미콜론 자동 삽입의 대상이 된다.
    • silent errors 의 원인이 될 수 있다.
  • num++ / num ++ 보다 num += 1 이 더 바람직하다.
  • 단항 증감을 사용하지 않으면,
    • pre-incrementing / pre-decrementing 실수를 방지할 수 있다.
// bad

const array = [1, 2, 3];
let num = 1;
num++;
--num;

let sum = 0;
let truthyCount = 0;
for (let i = 0; i < array.length; i++) {
  let value = array[i];
  sum += value;
  if (value) {
    truthyCount++;
  }
}

// good

const array = [1, 2, 3];
let num = 1;
num += 1;
num -= 1;

const sum = array.reduce((a, b) => a + b, 0);
const truthyCount = array.filter(Boolean).length;

= 할당문 전후로 줄바꿈 X, 줄바꿈이 필요하다면 () 사용 eslint operator-linebreak.


  • 할당문 전후로 줄바꿈이 발생하면 난독화를 일으킬 수 있다.
// bad
const foo =
  superLongLongLongLongLongLongLongLongFunctionName();

// bad
const foo
  = 'superLongLongLongLongLongLongLongLongString';

// good
const foo = (
  superLongLongLongLongLongLongLongLongFunctionName()
);

// good
const foo = 'superLongLongLongLongLongLongLongLongString';

사용하지 않은 변수는 비허용된다. . eslint: no-unused-vars


  • 선언되었지만 사용되지 않은 변수는 리팩토링이 완전하게 되지 않았다는 의미이다.
  • 코드 공간을 불필요하게 차지한다.
  • 읽는 사람에게 혼동을 준다.
// bad

var some_unused_var = 42;

// y 는 쓰여지기만 했지 사용되지 않았다.
var y = 10;
y = 5;

// 사용되지 않은 변수
var z = 0;
z = z + 1;

// 사용되지 않은 함수
function getX(x, y) {
    return x;
}

// good

function getXPlusY(x, y) {
  return x + y;
}

var x = 1;
var y = a + 2;

alert(getXPlusY(x, y));

// 나머지 프로퍼티 연산자: 객체에서 특정 키를 의도적으로 빠뜨리고 추출하는 방법이다. 
// 'type' 은 사용하지 않아도 괜찮다.
var { type, ...coords } = data;
// 'coords' 는 data 객체에서 'type' 프로퍼티가 빠진 객체다.