Loading repository data…
Loading repository data…
parksb / repository
Airbnb JavaScript 스타일 가이드
원문: https://github.com/airbnb/javascript
대체로 합리적인 JavaScript 접근 방법
참고: 이 가이드는 사용자가 Babel과 babel-preset-airbnb 또는 이와 동등한 것을 사용한다고 가정합니다. 또한 사용자가 어플리케이션에 airbnb-browser-shims와 함께 shims/polyfills 또는 이와 동등한 것을 설치했다고 가정합니다.
이 스타일 가이드는 다른 언어로도 제공됩니다. Translation을 보세요.
다른 스타일 가이드
1.1 원시형: 원시형에 접근하면 값을 직접 조작하게 됩니다.
stringnumberbooleannullundefinedsymbolbigintconst foo = 1;
let bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 9
1.2 참조형: 참조형에 접근하면 참조를 통해 값을 조작하게 됩니다.
objectarrayfunctionconst foo = [1, 2];
const bar = foo;
bar[0] = 9;
console.log(foo[0], bar[0]); // => 9, 9
2.1 모든 참조에는 var 대신 const를 사용하세요. eslint: prefer-const, no-const-assign
왜? 참조를 재할당 할 수 없게 함으로써, 이해하기 어려운 동시에 버그로 이어지는 코드를 방지합니다.
// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;
2.2 만약 참조를 재할당 해야 한다면 var 대신 let을 사용하세요. eslint: no-var
왜?
var처럼 함수스코프를 취하는 것 보다는 블록스코프를 취하는let이 더 낫습니다.
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
2.3 let 과 const 는 둘 다 블록스코프라는 것을 유의하세요.
// const와 let은 선언된 블록 안에서만 존재합니다.
{
let a = 1;
const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError
3.1 객체를 생성할 때는 리터럴 문법을 사용하세요. eslint: no-new-object
// bad
const item = new Object();
// good
const item = {};
3.2 동적 속성을 갖는 객체를 생성할 때는 속성 계산명을 사용하세요.
왜? 이렇게 하면 객체의 모든 속성을 한 곳에서 정의할 수 있습니다.
function getKey(k) {
return `a key named ${k}`;
}
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
3.3 메소드의 단축구문을 사용하세요. eslint: object-shorthand
// bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};
3.4 속성의 단축구문을 사용하세요. eslint: object-shorthand
왜? 설명이 간결해지기 때문입니다.
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
lukeSkywalker: lukeSkywalker,
};
// good
const obj = {
lukeSkywalker,
};
3.5 속성의 단축구문은 객체 선언의 시작 부분에 모아주세요.
왜? 어떤 속성이 단축구문을 사용하고 있는지 알기 쉽게 해줍니다.
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
episodeOne: 1,
twoJediWalkIntoACantina: 2,
lukeSkywalker,
episodeThree: 3,
mayTheFourth: 4,
anakinSkywalker,
};
// good
const obj = {
lukeSkywalker,
anakinSkywalker,
episodeOne: 1,
twoJediWalkIntoACantina: 2,
episodeThree: 3,
mayTheFourth: 4,
};
3.6 유효하지 않은 식별자에만 따옴표 속성을 사용하세요. eslint: quote-props
왜? 더 읽기 쉽습니다. 이렇게 하면 구문 하이라이팅이 잘 되고, 많은 자바스크립트 엔진이 더 쉽게 최적화 할 수 있습니다.
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
3.7 hasOwnProperty, propertyIsEnumerable, isPrototypeOf와 같은 Object.prototype 메소드를 직접 호출하지 마세요. eslint: no-prototype-builtins
왜? 이러한 메소드들은 객체의 속성에 의해 가려질 수 있습니다. -
{ hasOwnProperty: false }- 또는, 객체가 null 객체(Object.create(null))일 수도 있습니다.
// 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));
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
3.8 객체에 대해 얕은 복사를 할 때는 Object.assign대신 객체 전개 구문을 사용하세요. 특정 속성이 생략된 새로운 개체를 가져올 때는 객체 나머지 연산자(object rest operator)를 사용하세요. eslint: prefer-object-spread
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // `original`을 변조합니다 ಠ_ಠ
delete copy.a; // 그래서 이렇게 합니다
// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
// 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 }
4.1 배열을 생성할 때 리터럴 구문을 사용하세요. eslint: no-array-constructor
// bad
const items = new Array();
// good
const items = [];
4.2 배열에 직접 값을 할당하지 말고 Array#push를 사용하세요.
const someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');
4.3 배열을 복사할 때는 배열 전개 구문 ... 을 사용하세요.
// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i += 1) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];
4.4 순회 가능한 객체(iterable object)를 배열로 변환할 때는 Array.from 대신 전개 구문 ...을 사용하세요.
const foo = document.querySelectorAll('.foo');
// good
const nodes = Array.from(foo);
// best
const nodes = [...foo];
4.5 array-like 객체를 배열로 변환할 때는 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);
4.6 매핑할 때는 전개 구문 ... 대신 Array.from을 사용하세요. 중간 배열 생성을 방지하기 때문입니다.
// bad
const baz = [...foo].map(bar);
// good
const baz = Array.from(foo, bar);