종우공간 2021. 7. 28. 08:25

신텍스와 예제

const color = 'red';

switch(color) {
    case 'red':
        console.log('Color is red');
        break;
    case 'blue':
        console.log('Color is blue');
        break;
    default:
        console.log('Color is not red or blue');
        break;
}
//yields 'Color is red'
switch(new Date().getDay()) {
    case 0:
        day = 'Sunday';
        break;
    case 1:
        day = 'Monday';
        break;
    case 2:
        day = 'Tuesday';
        break;
    case 3:
        day = 'Wednesday';
        break;
    case 4:
        day = 'Thursday';
        break;
    case 5:
        day = 'Friday';
        break;
    case 6:
        day = 'Sunday';
        break;
}
console.log(`Today is ${day}`); //yields 'Today is Tuesday'(depends on the real day)

- case마다 break를 사용함으로써 특정한 case에 속할 경우 다른 case까지 가지 않도록 한다.

- switch문은 두번 째 예제와 같이 case가 많은 경우 사용하며, if-statements 보다 보기 훨씬 깔끔하다.