2018. 9. 24. 13:04 Back-End/Node
Node 프로그래밍 시 유의사항 ver.16 쉼표 (Commas) & 세미콜론 (Semicolons) & 형변환과 강제 (Type Casting & Coercion)
// 출처 https://github.com/ParkSB/javascript-style-guide#%EB%AA%A9%EC%B0%A8
// 쉼표 (Commas) & 세미콜론 (Semicolons) & 형변환과 강제 (Type Casting & Coercion)
// 1 맨 앞의 쉼표: 안 됩니다. eslint: comma-style
// 2 끝의 쉼표: 좋아요. eslint: comma-dangle
// bad
const hero = {
firstName: 'Dana',
lastName: 'Scully'
};
const heroes = [
'Batman',
'Superman'
];
// good
const hero = {
firstName: 'Dana',
lastName: 'Scully',
};
const heroes = [
'Batman',
'Superman',
];
// bad
function createHero(
firstName,
lastName,
inventorOf
) {
// does nothing
}
// good
function createHero(
firstName,
lastName,
inventorOf,
) {
// does nothing
}
// good (note that a comma must not appear after a "rest" element)
function createHero(
firstName,
lastName,
inventorOf,
...heroArgs
) {
// does nothing
}
// bad
createHero(
firstName,
lastName,
inventorOf
);
// good
createHero(
firstName,
lastName,
inventorOf,
);
// good (note that a comma must not appear after a "rest" element)
createHero(
firstName,
lastName,
inventorOf,
...heroArgs
);
// 3 세미콜론 씁시다. eslint: semi
// 4 구문의 선두에서 형을 강제합니다.
// 5 문자열: eslint: no-new-wrappers
// => this.reviewScore = 9;
// bad
const totalScore = new String(this.reviewScore);
// typeof totalScore is "object" not "string"
// bad
const totalScore = this.reviewScore + '';
// invokes this.reviewScore.valueOf()
// bad
const totalScore = this.reviewScore.toString();
// isn’t guaranteed to return a string
// good
const totalScore = String(this.reviewScore);
// 6 숫자: 형변환을 하는 경우 Number를 사용하고, 문자열을 파싱하는 경우에는
기수를 인자로 넘겨 parseInt를 사용하세요. eslint: radix no-new-wrappers
const inputValue = '4';
// bad
const val = new Number(inputValue);
// bad
const val = +inputValue;
// bad
const val = inputValue >> 0;
// bad
const val = parseInt(inputValue);
// good
const val = Number(inputValue);
// good
const val = parseInt(inputValue, 10);
// 7 어떤 이유로 인해 parseInt가 병목현상을 일으켜 성능적인 이유로
비트 시프트를 사용해야 하는 경우 하려고 했던 것을
왜(why)와 무엇(what)으로 설명해 주석으로 남겨주세요.
// good
/**
* parseInt was the reason my code was slow.
* Bitshifting the String to coerce it to a
* Number made it a lot faster.
* 코드가 느린 원인은 parseInt였음.
* 비트 시프트를 통해 문자열을 강제 형변환하여
* 성능을 개선시킴.
*/
const val = inputValue >> 0;
// 8 주의: 비트 연산자를 사용하는 경우. 숫자는 64비트 값으로 표현되어 있으나,
비트 시프트 연산을 한 경우 32비트 정수로 넘겨집니다. (소스). 32비트 이상의 정수를
비트 시프트하는 경우 예기치못한 현상을 야기할 수 있습니다. 토론.
부호가 포함된 32비트 정수의 최대치는 2,147,483,647입니다:
// 9 불리언: eslint: no-new-wrappers
const age = 0;
// bad
const hasAge = new Boolean(age);
// good
const hasAge = Boolean(age);
// best
const hasAge = !!age;