JavaScript #13 ~ The Switch Statement

HJ's Coding Journey·2021년 6월 22일
0

[Learn] JavaScript

목록 보기
14/20

The switch statement is simply an alternative method to the if/else statement. Although it is not used commonly today, the switch statement method details a very concise format of how the code functions in a conditional structure. The case keyword would act as the if/else keywords in separating specific conditional statements. The break keywords is used in the switch statement to stop the code from running further when one of the conditions are met. Without the break keyword, the code would just keep running.

const day = 'friday';
switch (day) {
    case 'monday': // day === 'monday'
        console.log('Plan to study coding');
        console.log('Go to coding meetup');
        break;
    case 'tuesday':
        console.log('Prepare theory videos');
        break;
    case 'wednesday':
    case 'thursday':
        console.log('Write code examples');
        break;
    case 'friday':
        console.log('Record videos');
        break;
    case 'saturday':
    case 'sunday':
        console.log('Enjoy the weekend :D');
        break;
    default:
        console.log('Not a valid day!');
}

The switch statement functions exactly like the if/else statement. As such both would output the same results.

if (day === 'monday') {
    console.log('Plan to study coding');
    console.log('Go to coding meetup');
} else if (day === 'tuesday') {
    console.log('Prepare theory videos');
} else if (day === 'wednesday' || day === 'thursday') {
    console.log('Write code examples');
} else if (day === 'friday') {
    console.log('Record videos');
} else if (day === 'saturday' || 'sunday') {
    console.log('Enjoy the weekend :D');
} else {
    console.log('Not a valid day!');
}
profile
Improving Everyday

0개의 댓글