JavaScript / 조건문 / if, else if, else
특정 조건 만족 시 어떤 작업을 수행하고 싶을 때 사용하는 것이 if, else if, else입니다.
문법
if ( condition1 ) { statement1 }
condition1을 만족하면 statement1을 실행합니다.
if ( condition1 ) { statement1 } else { statement2 }
condition1을 만족하면 statement1을 실행하고, 만족하지 않으면 statement2를 실행합니다.
if ( condition1 ) { statement1 } else if ( condition2 ) { statement2 }
condition1을 만족하면 statement1을 실행하고, condition2을 만족하면 statement2을 실행합니다.
if ( condition1 ) { statement1 } else if ( condition2 ) { statement2 } else { statement3 }
condition1을 만족하면 statement1을 실행하고, condition2을 만족하면 statement2을 실행하고, 둘 다 만족하지 않으면 statement3을 실행합니다.
예제
숫자를 입력하면 10보다 작은지, 10인지, 10보다 큰지 알려주는 예제입니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript | if</title> </head> <body> <script> var jbNum = prompt( 'Enter Number', '' ); if ( jbNum < 10 ) { document.write ( '<p>Your number is less than 10.</p>' ); } else if ( jbNum == 10 ) { document.write ( '<p>Your number is 10.</p>' ); } else { document.write ( '<p>Your number is greater than 10.</p>' ); } </script> </body> </html>
예를 들어 20을 입력하면 다음과 같이 나옵니다.