if문은 조건에 따라서 코드를 실행함.
if(condition) {
// if-statement
}
if(condition) {
// if-statements
} else {
// else statements;
}
조건 간단하면 삼항 연산자가 보기 편함.
const max = 100;
let counter = 100;
counter < max ? counter++ : counter = 1;
console.log(counter);
let discount: number;
let itemCount = 11;
if (itemCount > 0 && itemCount <= 5) {
discount = 5; // 5% discount
} else if (itemCount > 5 && itemCount <= 10) {
discount = 10; // 10% discount
} else {
discount = 15; // 15%
}
console.log(`You got ${discount}% discount. `)
위 코드에서는 itemcount가 0보다 같거나 작을 경우를 상정하지 않았기 때문에 아래처럼 만드는게 좋음.
let discount: number;
let itemCount = 11;
if (itemCount > 0 && itemCount <= 5) {
discount = 5; // 5% discount
} else if (itemCount > 5 && itemCount <= 10) {
discount = 10; // 10% discount
} else if (discount > 10) {
discount = 15; // 15%
} else {
throw new Error('The number of items cannot be negative!');
}
console.log(`You got ${discount}% discount. `)
- if문으로 조건에 기반하여 코드 실행가능
- else로 if가 false일 경우 실행가능함. 간단한 if...else문일 경우 삼항연산자가 가독성 더 높음.
- if else if...else로 여러 조건 추가가능