개발/HTML, CSS, JS
[자바스크립트] if else 조건문과 삼항연산자
두두나 Designer
2023. 6. 2. 14:11
if else 조건문 2개
if(조건식){
참일때 실행문
} else if (2번째 조건식){
1번째 조건식이 거짓이고 2번째 조건식이 참일때 실행문
} else {
1,2번째 조건식이 거짓이고 3번째 조건식이 참일때 실행문
}
if else → 삼항연산자로 표현
if else 조건문은 삼항연산자로 바꿔 쓸 수 있다.
간단한 조건문은 삼항 연산자로 쓰면 간단하게 표현 할 수 있기 때문에 자주 쓰인다.
삼항 연산자로 표현하는 식을 많이 연습을 하면 좋다.
let age = 15;
if(age < 19) {
msg = “The user is not an adult.”;
}else{
msg = “The user is an adult.”;
}
console.log(msg); // The user is not an adult.
msg_another = age < 19 ? “The user is not an adult.” : “The user is an adult.”;
console.log(msg_another); // The user is not an adult.