본문 바로가기

개발/JavaScript

[Javascript] 좋은 변수명을 짓는 방법 (coding convention)

기본사항

  • 변수명은 자체 설명적이어야 한다.
// bad
const value = 'Robin';
const val = 'Robin';

// good
const firstName = 'Robin';
  • 자바스크립트에서는 camelCase, PascalCase를 사용한다.

Arrays

변수 이름을 복수화 하기

// bad 
const fruit = ['apple', 'banana', 'cucumber'];
// okay 
const fruitArr = ['apple', 'banana', 'cucumber'];
// good 
const fruits = ['apple', 'banana', 'cucumber'];
// great 
const fruitNames = ['apple', 'banana', 'cucumber'];
const fruits = [
	{ name: "apple", genus: "malus" },
	{ name: "banana", genus: "musa" },
	{ name: "cucumber", genus: "cucumis" },
];

Booleans

is, has, can로 시작하여 변수의 타입을 암시하기

// bad 
const open = true;
const write = true;
const fruit = true;

// good 
const isOpen = true;
const canWrite = true;
const hasFruit = true;

만약 함수의 return 값이 boolean이라면?

함수명을 check나 get으로 시작하기

const user = { fruits: ["apple"] };
const checkHasFruit = (user, fruitName) => user.fruits.includes(fruitName);
const hasFruit = checkHasFruit(user, "apple");

Numbers

변수명에 maximum, minimum, total 포함하기

// bad
const pugs = 3;

// good
const minPugs = 1;
const maxPugs = 5;
const totalPugs = 3;

Functions

동사나 명사 사용하여 명명하기

// bad
userData(userId);
userDataFunc(userId);
totalOfItems(items);

// good
getUser(userId);
calculateTotal(items);

to를 앞에 명명하는 것은 오래된 컨벤션이다

toDollars('euros', 20);
toUppercase('a string');

반복문 안에서의 변수는 단수형을 사용하기

// bad
const newFruits = fruits.map(x => {return doSomething(x);});

// good
const newFruits = fruits.map(fruit => {return doSomething(fruit);});

Components & Class

컴포넌트는 클래스와 같이 대문자로 사용한다

// bad
function userProfile(user) {
  return (
    <div>
      <span>First Name: {user.firstName}</span>
      <span>Last Name: {user.lastName}</span>
    </div>
  );
}

// good
function UserProfile(user) {
  return (
    <div>
      <span>First Name: {user.firstName}</span>
      <span>Last Name: {user.lastName}</span>
    </div>
  );
}

Constant

const 형은 대문자에 _를 사용한다.

var SECONDS = 60;
var MINUTES = 60;
var HOURS = 24;
var DAY = SECONDS * MINUTES * HOURS;
var DAYS_UNTIL_TOMORROW = 1;

reference

https://hackernoon.com/the-art-of-naming-variables-52f44de00aad

https://www.robinwieruch.de/javascript-naming-conventions/