JavaScript에서의 조건 분기
이 글은 JavaScript에서의 조건 분기에 대해 설명합니다.
YouTube Video
JavaScript의 if
문
기본 구문
1if (condition) {
2 // Code that executes if the condition is true
3}
JavaScript의 if
문은 특정 조건이 참인지 거짓인지에 따라 코드 실행을 제어하는 기본적인 제어 구조입니다. 조건이 참일 경우 해당 코드 블록이 실행되고, 거짓일 경우 건너뜁니다.
예제
1let x = 10;
2
3if (x > 5) {
4 console.log("x is greater than 5");
5}
이 예에서는 x
의 값이 5
보다 크기 때문에 x is greater than 5
가 콘솔에 표시됩니다.
else
문
기본 구문
1if (condition) {
2 // Code that executes if the condition is true
3} else {
4 // Code that executes if the condition is false
5}
if
문 뒤에 else
문을 사용하여 조건이 거짓일 때 실행할 코드를 지정할 수 있습니다.
예제
1let x = 3;
2
3if (x > 5) {
4 console.log("x is greater than 5");
5} else {
6 console.log("x is 5 or less");
7}
이 경우, x
가 5
보다 작기 때문에 "x is 5 or less"
가 표시됩니다.
else if
문
기본 구문
1if (condition1) {
2 // Code that executes if condition1 is true
3} else if (condition2) {
4 // Code that executes if condition1 is false and condition2 is true
5} else {
6 // Code that executes if both condition1 and condition2 are false
7}
여러 조건을 확인하려면 else if
를 사용하세요. 처음 if
조건이 거짓이면 다음 조건이 확인됩니다.
예제
1let x = 5;
2
3if (x > 10) {
4 console.log("x is greater than 10");
5} else if (x === 5) {
6 console.log("x is 5");
7} else {
8 console.log("x is 5 or less");
9}
이 경우, x
가 5이므로 "x is 5"
가 표시됩니다.
삼항 연산자 (조건 연산자)
문법
1condition ? valueIfTrue : valueIfFalse
if
문을 더 간결하게 작성하려면 삼항 연산자를 사용할 수 있습니다.
예제
1const number = 7;
2const result = number % 2 === 0 ? "Even" : "Odd";
3console.log(result); // "Odd"
이 경우, number
가 7
이기 때문에 Odd
가 표시됩니다.
요약
if
문은 조건이 참인지 거짓인지에 따라 실행되는 코드를 제어합니다.else
를 사용하여 조건이 거짓일 때의 동작을 지정할 수 있습니다.else if
를 사용하여 여러 조건을 확인할 수 있습니다.- 삼항 연산자를 사용하여 조건 분기를 간결하게 작성할 수도 있습니다.
JavaScript의 switch
문
기본 구문
1switch (expression) {
2 case value1:
3 // Code that executes if the expression matches value1
4 break;
5 case value2:
6 // Code that executes if the expression matches value2
7 break;
8 default:
9 // Code that executes if no cases match
10}
JavaScript의 switch
문은 하나의 표현식(일반적으로 변수)을 여러 값(케이스)과 비교하고, 해당하는 코드를 실행하는 데 사용됩니다. if
문과 마찬가지로 조건 분기를 수행하지만, 여러 조건이 있을 때 가독성이 더 높은 경우가 있습니다.
예제
1let fruit = "apple";
2
3switch (fruit) {
4 case "apple":
5 console.log("This is an apple");
6 break;
7 case "banana":
8 console.log("This is a banana");
9 break;
10 default:
11 console.log("Unknown fruit");
12}
이 예제에서, fruit
가 "apple"
이기 때문에, "This is an apple"
이 콘솔에 출력됩니다.
break
の役割
각 경우의 끝에 break
를 삽입하면, 해당 경우를 완료한 후 switch
문에서 빠져나옵니다. break
를 작성하지 않으면, 다음 경우도 실행됩니다 (이는 fall-through라고 합니다).
Fall-Through 예제
1let color = "red";
2
3switch (color) {
4 case "red":
5 console.log("This is red");
6 case "blue":
7 console.log("This is blue");
8 default:
9 console.log("Unknown color");
10}
이 경우, color
가 "red"
이며, "This is red"
이후에 break
가 없기 때문에, "This is blue"
와 "Unknown color"
도 표시됩니다.
default
사용하기
default
는 어떠한 case
와도 일치하지 않을 때 실행되는 부분입니다. 이는 if
문에서의 else
와 동일합니다.
1let animal = "dog";
2
3switch (animal) {
4 case "cat":
5 console.log("This is a cat");
6 break;
7 case "bird":
8 console.log("This is a bird");
9 break;
10 default:
11 console.log("Unknown animal");
12}
이 경우, animal
이 "dog"
이므로, 이는 default
에 해당하며 "Unknown animal"
이 표시됩니다.
동일한 경우에 여러 값 처리하기
여러 경우에 대해 동일한 작업을 수행하려면, 이를 연속적으로 작성할 수 있습니다.
예제
1let day = 1;
2switch (day) {
3 case 1:
4 case 2:
5 case 3:
6 case 4:
7 case 5:
8 console.log("Weekday");
9 break;
10 case 6:
11 case 7:
12 console.log("Weekend");
13 break;
14 default:
15 console.log("Unknown day");
16}
이 예제에서, day
가 1
일 경우, "Weekday"
가 표시됩니다.
switch
vs. if
if
문은 복잡한 조건이나 범위를 확인하는 데 적합합니다. 예를 들어, 변수x
가 10보다 크거나 같고 20보다 작거나 같은 복잡한 조건은switch
에 작성할 수 없습니다.switch
문은 값이 특정 값과 일치하는지 확인할 때 코드의 가독성을 높일 수 있습니다.
요약
switch
문은 여러 값에 대한 조건 분기를 간결하게 작성하는 데 사용됩니다.case
의 끝에break
를 사용하지 않으면 다음case
도 실행될 수 있습니다 (fall-through).default
는 어느 경우와도 일치하지 않을 때 실행됩니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.