함께 성장하는 프로독학러

switch 조건문 본문

Programming/javascript

switch 조건문

프로독학러 2018. 4. 27. 11:20

안녕하세요, 프로독학러 입니다.


이번 포스팅에서는 자바스크립트의 조건문 중 하나인 switch 문에 대해서 알아보도록 하겠습니다.


switch 문의 표현식은 다음과 같습니다.


switch (expression) {
  case value1:
    //Statements executed when the result of expression matches value1
    [break;]
  case value2:
    //Statements executed when the result of expression matches value2
    [break;]
  ...
  case valueN:
    //Statements executed when the result of expression matches valueN
    [break;]
  default:
    //Statements executed when none of the values match the value of the expression
    [break;]
}

expression 은 표현식으로, 표현식의 결과로 예상되는 것을 case 의 value 로 사용합니다.

expression 과 case valueN 의 일치여부는 ===(일치연산자) 를 통해 확인합니다.

case 의 확인은 break 를 만날 때 까지 이루어 집니다.

default 는 expression 이 모든 case 가 일치하지 않을 경우에 실행되는 코드입니다.


if 문으로 표현한다면 다음과 같습니다.


1
2
3
4
5
6
7
8
9
if (expression ===  value1){
    //Statements executed when the result of expression matches value1
else if (expression ===  value2){
    //Statements executed when the result of expression matches value2
} ... else if (expression ===  valueN){
    //Statements executed when the result of expression matches valueN
else {
    //Statements executed when none of the values match the value of the expression
}
cs


switch 문은 break 를 만날 때 까지 종료되지 않으므로 다음과 같은 표현도 가능해 집니다.


1
2
3
4
5
6
7
8
9
10
11
12
var Animal = 'Giraffe';
switch (Animal) {
  case 'Cow':
  case 'Giraffe':
  case 'Dog':
  case 'Pig':
    console.log('This animal will go on Noah\'s Ark.');
    break;
  case 'Dinosaur':
  default:
    console.log('This animal will not.');
}
cs


Animal 의 값이 Cow, giraffe, Dog, Pig 중 하나라도 만족한다면 일 경우 7번째의 코드가 실행됩니다.


switch 문은 여러개의 조건을 비교하는데 효과적입니다.

물론 같은 코드를 if 조건문을 이용하여 작성할 수도 있지만 if 문은 코드의 중복이 많이 발생할 수 있으므로 여러개의 조건을 비교할 때는 switch 문을 이용하는 것이 효율적입니다.


여기까지 자바스크립트의 switch 조건문에 대해 알아보았습니다.

감사합니다.


**참고 자료 (항상 감사드립니다)

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/switch


*다녀가셨다는 표시는 공감으로 부탁드릴게요! (로그인 하지 않으셔도 공감은 가능합니다 ㅎㅎ)

Comments