자바스크립트 if문 더 간결하게 쓰는 방법, 들여쓰기(indentation) 생략

자바스크립트 if문 더 간결하게 쓰는 방법

들여쓰기 생략하기

첫 글자에 들여쓰기를 하면 모니터로 볼 수 있는 화면이 그만큼 작아지기 때문에 보기 힘들다. 이 때 indentation (들여쓰기)를 생략해주면 좋다.

#1 if (수정 전)
function checkSpeed(speed) {
const speedLimit = 70;
const kmPerPoint = 5;

if (speed < speedLimit + kmPerPoint) console.log('Ok');
else {
const points = Math.floor((speed - speedLimit) / kmPerPoint);
if (points >= 12) console.log('License suspended');
console.log('Point:', points);
}
}


if와 else를 쓰면서 else 뒤로는 다 들여쓰기가 적용되어 있다.

const points = Math.floor((speed - speedLimit) / kmPerPoint);
if (points >= 12) console.log('License suspended');
console.log('Point:', points);




(수정 후)

function checkSpeed(speed) {
const speedLimit = 70;
const kmPerPoint = 5;

if (speed < speedLimit + kmPerPoint) {
console.log('Ok');
return;
}
const points = Math.floor((speed - speedLimit) / kmPerPoint);
if (points >= 12) console.log('License suspended');
console.log('Point:', points);
}

처음 if문에 console.log 후 'return;'을 씀으로써 speed가 speedLimit + kmPerPoint 보다 작으면 'Ok'를 출력한 뒤 함수를 종료하게 설정했다.

덕분에 아래에 else와 들여쓰기(indentation)를 쓸 필요가 없으므로 삭제했다.

훨씬 깔끔한 코드 완성!

댓글

이 블로그의 인기 게시물

비전공자가 Chat GPT만 가지고 영작 연습 웹사이트 만들 수 있을까?

자바스크립트 깔끔한 코딩을 위한 필수 개념