⊗jsPmCdSwCs 129 of 502 menu

switch-case construct in JavaScript

Using the switch-case construct, you can run different code, depending on the value of the variable. Here is the syntax for this construct:

switch (variable) { case 'value1': /* here is the code that will be executed if the variable has value1 */ break; case 'value2': /* here is the code that will be executed if the variable has value2 */ break; case 'value3': /* here is the code that will be executed if the variable has value3 */ break; default: /* here is the code that will be executed if it does not match any value */ break; }

Let's write a code example with the switch-case construct:

let num = 1; switch (num) { case 1: console.log('value1'); break; case 2: console.log('value2'); break; case 3: console.log('value3'); break; default: console.log('incorrect value'); break; }

Rewrite the following code with switch-case:

let lang = 'ru'; if (lang == 'ru') { console.log('rus'); } else if (lang == 'en') { console.log('eng'); } else if (lang == 'de') { console.log('deu'); } else { console.log('language not supported'); }
enru