조건문은 다른 조건에 따라 다른 작업을 수행하는 데 사용된다.
코드를 작성할 때 서로 다른 결정에 대해 서로 다른 작업을 수행하려는 경우가 많다.
이를 위해 코드에서 조건문을 사용할 수 있다.
JavaScript에는 다음과 같은 조건문이 있다.
true
인 경우 실행할 코드 블록을 지정하려면 if
를 사용한다.false
인 경우 else
를 사용하여 실행할 코드 블록을 지정한다.false
인 경우 테스트할 새 조건을 지정하려면 else if
를 사용한다.switch
를 사용한다.
switch
문은 다음 장에서 배우자.
if
문을 사용하여 조건이 true
인 경우 실행할 JavaScript 코드 블록을 지정한다.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
if
는 소문자다. 대문자(If 또는 IF)는 JavaScript 오류를 생성한다.
첫 번째 조건이 false
인 경우 else if
문을 사용하여 새 조건을 지정한다.
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
}
아래 예시에서는 W3Schools 또는 WWF(세계 야생 동물 재단)에 대한 링크를 연결시킨다. 난수를 사용하면 각 링크에 대해 50%의 확률이 있다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p id="demo"></p>
<script>
let text;
if (Math.random() < 0.5) {
text = "<a href='https://w3schools.com'>Visit W3Schools</a>";
} else {
text = "<a href='https://wwf.org'>Visit WWF</a>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>