if 문 안에 있는 조건식이 참인 경우 해당하는 조건식의 영역을 실행. 조건문은을 여러 개 조합히기 위해서는 else if를 사용. 조건문의 조건이 어느 것도 충족되지 않으며 그대로 skip 하거나 else 구문을 실행.
** 다른 언어에서도 많이 쓰이는 구문이다 **
조건식을 거짓을 판단하는 반환값
false
undefined
null
0
빈 문자열("")
NaN(Not a Number // 표현 불가능한 수치형 결과)
if .. else
graph TD A[start] --> B{Condition} B -->|true| C[if block] B -->|false| D[else block] C --> E[end] D --> E[end]
if (조건) {
만약 조건(condition)이 참일 경우 실행할 코드
} else {
대신 실행할 다른 코드
}
if ...else if ... else
constselect = document.querySelector("select");
const para = document.querySelector("p");
select.addEventListener("change", setWeather);
function setWeather() {
const choice = select.value;
if (choice === "sunny") {
para.textContent =
"It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.";
} elseif (choice === "rainy") {
para.textContent =
"Rain is falling outside; take a rain coat and a brolly, and don't stay out for too long.";
} else {
para.textContent = "";
}
}
switch 문
switch 문에는 연산식이나 변수가 들어감. case 뒤에는 switch 문에 있는 연산이나 변수의 예상하는 결과값을 기입하며, 결과값에 해당하는 case에서 하단에 작성된 코드를 실행항. default는 else와 마찬가지로 모든 case에 해당되지 않을 경우 실행하는 부분.