JavaScript에서 조건에 따라 로직을 실행하는 흔한 방법은 if문이에요.
if 키워드, 소괄호로 감싼 조건, 그리고 중괄호로 감싼 코드 블록으로 이루어져 있어요.
코드 블록은 조건이 true로 평가될 때만 실행돼요.
if (condition) {
// code that is executed if "condition" is true
}
단독으로 사용할 수도 있고, else 키워드와 함께 사용할 수도 있어요.
if (condition) {
// code that is executed if "condition" is true
} else {
// code that is executed otherwise
}
if문else문에 또 다른 조건을 중첩하려면 else if를 사용할 수 있어요.
JavaScript에는 elseif 키워드가 없다는 점에 주의해요.
대신 else를 쓴 뒤 또 다른 if문을 이어서 써요.
if (condition1) {
// code that is executed if "condition1" is true
} else if (condition2) {
// code that is executed if "condition2" is true
// but "condition1" was false
} else {
// code that is executed otherwise
}
이론적으로는 조건을 원하는 만큼 더 중첩할 수 있어요.
하지만 실제로는 이런 경우 switch문을 대신 사용해요.
if (condition1) {
// ...
} else if (condition2) {
// ...
} else if (condition3) {
// ...
} else if (condition4) {
// ...
} else {
// ...
}
복잡한 조건을 만들 때는 불필요한 괄호를 피하기 위해 연산자 우선순위 표를 참고해요.
if (num >= 0 && num < 1) {
// ...
}
// The inner brackets are obsolete because relational operators
// have higher precedence than logical operators.
<!-- prettier-ignore-start -->
if ((num >= 0) && (num < 1)) {
// ...
}
<!-- prettier-ignore-end -->
또한 변수를 추가로 사용하면 코드를 더 읽기 쉽게 만들 수 있어요.
const isPositive = num >= 0;
const isSmall = num < 1;
if (isPositive && isSmall) {
// ...
}
JavaScript에서 조건은 반드시 불리언 타입일 필요는 없어요.
if문 같은 불리언 문맥에 불리언이 아닌 다른 타입의 값이 들어오면, JavaScript는 그 값을 불리언으로 암시적으로 변환해요.
어떤 값이 각각 _truthy_와 _falsy_인지에 대한 자세한 내용은 타입 변환 개념을 참고해요.
const num = 4;
if (num) {
// this code block will be executed because 4 is truthy
}
if나 else의 코드 블록에서 문을 하나만 실행하고 싶다면, JavaScript에서는 중괄호를 생략할 수 있어요.
if (condition) doSomething();
// or
if (condition)
doSomething();
예를 들어 오류 조건을 확인할 때 이런 방식을 쓰기도 해요. 하지만 일반적으로는 권장하지 않는데, 같은 조건에 따라야 하는 두 번째 문을 추가할 때 괄호를 다시 붙이는 걸 잊기 쉬우니까요.
함수를 작성할 때는 else 블록을 생략하고 대신 if 블록에서 return을 일찍 사용하는 패턴을 흔히 써요.
이렇게 하면 대부분의 경우 _중첩_이 줄어들고 코드가 더 읽기 쉽고 따라가기 쉬워져요.
function checkNumber(num) {
let message = '';
if (num === 0) {
message = 'You passed 0, please provide another number.';
} else {
message = 'Thanks for passing such a nice number.';
}
return message;
}
// Can also be written as ...
function checkNumber(num) {
if (num === 0) {
return 'You passed 0, please provide another number.';
}
return 'Thanks for passing such a nice number.';
}