
[참조] Airbnb JavaScript Style Guide
string boolean number null undefined symbol bigintobject array functionconst : 참조 재할당 X→ 버그 감소let : 참조 재할당 O ← 블록 범위var : 참조 재할당 O ← 함수 범위new Object() → {}const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};Object.prototype 메서드 직접 호출 X → .call 사용Object.assign 대신 ... (스프레드) 사용const copy = {...original, c: 3};
const {a, ...noA} = copy;new Array() → []Array#push 사용const itemsCopy = [...items];const [first, second] = arr;
// const first = arr[0]; const second = arr[1];'' 사용\ 사용 X${name}function foo() { ... } //Bad
const foo = function bar() { ... } //Good(function () {
console.log('Welcome to the Internet. Please follow me.');
}());{} 로 묶어주기... 사용function concatenateAll() { //Bad
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
function concatenateAll(...args) { //Good
return args.join('');
}function handleThings(opts = {}) { ... }new 생성자 사용 Xconst x = function a() {};function foo(
bar,
baz,
quux,
) { ... }[1, 2, 3].map(function (x) { //Bad
const y = x + 1;
return x * y;
});
[1, 2, 3].map((x) => { //Good
const y = x + 1;
return x * y;
});() 로 묶기() 항상 포함 : diff 변경 최소화extends 사용this사용import / export 사용import * as AirbnbStyleGuide from './AirbnbStyleGuide'; //Bad
import AirbnbStyleGuide from './AirbnbStyleGuide'; //Goodimport foo, { named1, named2 } from 'foo';default 사용export default function foo() {}webpack.config.js 에서 loader syntax 사용./foo.js → ./foomap() filter() find() findIndex() reduce() some() …Object.keys() Object.values() Object.entries()const numbers = [1, 2, 3, 4, 5];
// bad
let sum = 0;
for (let num of numbers) {
sum += num;
}
sum === 15;
// good
let sum = 0;
numbers.forEach((num) => {
sum += num;
});
sum === 15;
// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
// bad
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) {
increasedByOne.push(numbers[i] + 1);
}
// good
const increasedByOne = [];
numbers.forEach((num) => {
increasedByOne.push(num + 1);
});
// best (keeping it functional)
const increasedByOne = numbers.map((num) => num + 1);const foo = function* () {
// ...
};** 사용const let 사용 → 그렇지않으면 전역변수가 됨.let a = b = c = 1; //Badnum++ → num += 1= 연산자 전 후 라인 유지, break되면 괄호로 묶기var 선언은 hoisting 된다. (let, const는 X)function example() {
console.log(declaredButNotAssigned); // => undefined
var declaredButNotAssigned = true;
} //let, const였으면 referenceErrorfunction example() {
console.log(anonymous); // => undefined
anonymous(); // => TypeError anonymous is not a function
var anonymous = function () {
console.log('anonymous function expression');
};
}function example() {
console.log(named); // => undefined
named(); // => TypeError named is not a function
superPower(); // => ReferenceError superPower is not defined
var named = function superPower() {
console.log('Flying');
};
}function example() {
superPower(); // => Flying
function superPower() {
console.log('Flying');
}
}== != < === !==ToBoolean 추상 메서드 → 강제 변환{}switch (foo) {
case 1: {
let x = 1;
break;
}
case 2: {
const y = 2;
break;
}
case 3: {
function f() {
// ...
}
break;
}
case 4:
bar();
break;
default: {
class C {}
}
}+ - ++ 제외)??{} 사용if (test) return false;
if (test) {
return false;
}if while ) 길어지면 → 그룹화된 조건을 새로운 줄에 추가!isRunning && startRunning(); //Bad/** ... */ 사용/**
* make() returns a new element
* based on the passed-in tag name
*/// 새로운 줄에 추가FIXME : 파악해야하는 것 TODO : 구현해야하는 것 }추가// FIXME: shouldn’t use a global here
total = 0;
// TODO: total should be configurable by an options param
this.total = 0;x = y + 5$('#items')
.find('.selected')
.highlight()
.find('.open')
.updateCount();var foo = function() {};toString() +'' new String() 대신에 String() 사용Number() / 문자열 파싱 : parseInt() 기수와 함께const val = Number(inputValue);
const val = parseInt(inputValue, 10); //10진수로Bitshift 사용 시 주석 남기기new Boolean() Boolean() 대신 !! 사용const age = 0;
const hasAge = !!age;thisIsMyObjectUser_ __ 사용 Xthis 에 대한 참조 저장 X → 화살표 함수나 function#bind 사용import CheckBox from './CheckBox'; // PascalCase export/import/filename
import fortyTwo from './fortyTwo'; // camelCase export/import/filename
import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"SMSContainergetters setters 사용 X → 접근자 함수 만들기isVal() hasVal() 사용