Javascript
코드 품질 - 코딩 스타일
big whale
2021. 7. 2. 16:49
복잡한 문제를 간결하고 사람이 읽기 쉬운 코드로 작성해야 한다.
가로 길이
가로로 길게 늘어진 코드는 여러 줄로 나눠 작성하는게 좋다. 이때 백틱(`)을 사용하면 문자열을 여러 줄로 쉽게 나눌 수 있다.
let str = `
ECMA International's TC39 is a group of JavaScript developers,
implementers, academics, and more, collaborating with the community
to maintain and evolve the definition of JavaScript.
`;
if (
id === 123 &&
moonPhase === 'Waning Gibbous' &&
zodiacSign === 'Libra'
) {
alert(str);
}
과제
좋지 않은 코드 스타일 수정하기
function pow(x,n)
{
let result=1;
for(let i=0;i<n;i++) {result*=x;}
return result;
}
let x=prompt("x?",''), n=prompt("n?",'')
if (n<=0)
{
alert(`Power ${n} is not supported, please enter an integer number greater than zero`);
}
else
{
alert(pow(x,n))
}
수정후
function pow(x, n) {
let result = 1;
for(let i = 0; i < n; i++) {
result *= x;
}
return result;
}
let x = prompt("x?", '');
let n = prompt("n?", '');
if ( n <= 0 ) {
alert( `Power ${n} is not supported,
please enter an integer number greater than zero` );
} else {
alert( pow( x, n ) )
}