중괄호
들여쓰기
const leds = stage.selectAll('.led').data(data).enter()
.append('svg:svg').classed('led', true).attr('width', (radius + margin) * 2)
.append('svg:g').attr('transform', `translate(${radius + margin},${radius + margin})`)
.call(tron.led);
공백
줄 공백은 아래의 사항에서 나타날 수 있다.
// good
if (foo) {
return bar;
}
return baz;
// good
const obj = {
foo() {
},
bar() {
},
};
// good
const arr = [
function foo() {
},
function bar() {
},
];
return arr;
지역 변수는 그 변수를 포함하는 블록 시작에서 선언하지 않고, 사용 범위를 최소화하기 위해 사용되는 지점과 가장 가까운 곳에서 선언한다.
// good
function() {
test();
console.log('doing stuff..');
const name = getName();
if (name === 'test') {
return false;
}
return name;
}
변수를 선언할 때는 const를 사용한다.단, 변수의 값이 바뀌는 경우 let을 사용한다.
배열에 값을 넣을 때는 Array.push를 사용한다.
const someStack = [];
someStack.push('abracadabra');
// good
var my_object = {
"key": "value",
"key2": "value2",
};
// good
class Queue {
constructor(contents = []) {
this._queue = [...contents];
}
pop() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
}
// good
class PeekableQueue extends Queue {
peek() {
return this._queue[0];
}
}
class Jedi {
constructor(options = {}) {
this.name = options.name || 'no name'; // null이 반환되는 것을 방지
}
getName() {
return this.name;
}
toString() {
return `Jedi - ${this.getName()}`;
}
}
함수 내에 또다른 함수를 선언할 수 있다.
// good
function foo() { // 함수 전체가 hoist됨
}
함수식을 사용해야만한다면, 화살표 함수(Arrow Function)을 사용하라.
// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map(number => `A string containing the ${number}.`);
// good
[1, 2, 3].map(number => {
const nextNumber = number + 1;
return `A string containing the ${nextNumber}.`;
});
식이 여러 줄에 걸쳐있을 경우에 가독성을 위해 소괄호로 감싸 사용한다.
// good
[1, 2, 3].map(number => (
`As time went by, the string containing the ${number} became much ` +
'longer. So we needed to break it over multiple lines.'
));
80글자 이상의 긴 문자열을 여러 줄에 걸쳐 쓰기 위해서는 템플릿 리터럴 혹은 **문자열 연결( + )**을 사용한다.
// 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.';
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
function sayHi(name) {
return `How are you, ${name}?`;
}