JavaScript If...Else Statements
조건문(Conditional statements)은 다른 조건에 따라 서로 다른 작업을 수행하는 데 사용됩니다.
Conditional Statements
코드를 작성할 때 매우 자주, 다른 조건에 따라 다른 작업을 수행 하고 싶은 경우, 조건문을 사용할 수
있습니다.
JavaScript 에서는 다음과 같은 조건문이 있다 :
- if statement - 지정된 조건이 true 인 경우에만 특정 코드를 실행하려면 사용
- if...else statement - 조건이 true 이면 일부 코드를 실행하고, 조건이 false 인 경우에는 다른 코드를 실행하려면 사용
- if...else if....else statement - 많은 블록 중 하나를 선택하여 실행하려면 사용
- switch statement - 많은 블록 중 하나를 선택하여 실행하려면 사용
If 문
지정된 조건이 true 인 경우에만 코드를 실행하기 위해 if 문을 사용합니다.
Syntax
if (condition) {
block of code to be executed if the
condition is true
}
참고 if 는 소문자로 기록합니다. 대문자(IF)를 사용하면 자바 스크립트 오류가 발생합니다!
Example
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18)
{
greeting = "Good
day";
}
The result of greeting will be:
Good day
Try it Yourself »
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified condition is true.
If...else 문
조건이 true 이면 어떤 코드를 실행하고, true가 아닌 경우에는 다른 코드를 실행시키는데 if....else statement 를 사용합니다.
Syntax
if (condition) {
block of code to be executed if the
condition is true
}
else {
block of code to be executed if the
condition is false
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18)
{
greeting = "Good
day";
}
else {
greeting = "Good
evening";
}
The result of greeting will be:
Good day
Try it Yourself »
If...else if...else Statement
몇 개의 코드 블록 중에서 하나를 선택하려면 if....else if...else statement 를 사용한다.
Syntax
if (condition1) {
block of code to be executed if
condition1 is true
}
else if (condition2) {
block of code to be executed if the
condition1 is false and condition2 is true
} else {
block of code to be executed if the
condition1 is false and condition2 is false
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10)
{
greeting = "Good
morning";
}
else if
(time < 20) {
greeting = "Good
day";
}
else {
greeting = "Good
evening";
}
The result of greeting will be:
Good morning
Try it Yourself »
More Examples
Random
link
This example will write a link to either W3Schools or to the World
Wildlife Foundation (WWF). By using a random number, there is a
50% chance for each of the links.
Test Yourself with Exercises!
Exercise 1 » Exercise 2 » Exercise 3 » Exercise 4 » Exercise 5 » Exercise 6 »