목차
조건문이란?
조건문(Conditional Statement)은 프로그래밍에서 사용되는 제어 구조 중 하나로, 프로그램이 특정 조건에 따라 다른 동작을 수행하도록 하는 데 사용된다.
조건문 연습을 위해 prompt로 사용자의 나이를 묻고 입력받은 나이별로 메세지를 산출하는 코드를 작성해보자.
const age = parseInt(prompt("How old are you.")); if (isNaN(age) || age < 0) { console.log("Please write a real positive number."); } else if (age < 18) { console.log("You are too young."); } else if (age >= 18 && age <= 50) { console.log("You can drink."); } else if (age > 50 && age <= 80) { console.log("You should exercise."); } else if (age > 80) { console.log("You can do whatever you want."); }
세부 설명:
if (isNaN(age) || age < 0) { console.log("Please write a real positive number."); }
입력 받은 나이가 숫자가 아니거나(isNaN) 음수일때(age<0) "Please write a real positive number." 메세지 호출
|| 는 OR이다. 둘 중 하나가 true 면 true.
else if (age < 18) { console.log("You are too young.");
18세 미만이면 "You are too young" 호출
else if (age >= 18 && age <= 50) { console.log("You can drink.");
18세~50세 이면 "You can drink" 호출
&& 은 AND 이다. 둘 다 만족해야 true.
else if (age > 50 && age <= 80) { console.log("You should exercise."); }
50세 초과 이고 80세 이하이면(51~80세) "You should exercise." 호출
else if (age > 80) { console.log("You can do whatever you want."); }
80세 초과이면 "You can do whatever you want." 호출