The switch keyword


#1

I understand that the switch(lets call it a function) matches strings like:

‘’’
let athleteFinalPosition = ‘first place’;

switch (athleteFinalPosition) {
case ‘first place’:
console.log(‘You get the gold medal!’);
break;
case ‘second place’:
console.log(‘You get the silver medal!’);
break;
case ‘third place’:
console.log(‘You get the bronze medal!’);
break;
default:
console.log(‘No medal awarded.’);
break;
}
‘’’
but does it match expressions like:

‘’’
let athleteFinalPosition = 1;

switch (athleteFinalPosition) {
case 3-2:
console.log(‘You get the gold medal!’);
break;
case 4-2:
console.log(‘You get the silver medal!’);
break;
case 5-2’:
console.log(‘You get the bronze medal!’);
break;
default:
console.log(‘No medal awarded.’);
break;
}
‘’’

link to exercise: https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/learn-javascript-control-flow/lessons/control-flow/exercises/switch


#2
switch (expression) {
case expression1: action; break;
case expression2: action; break;
case expression3: action; break;
default: action; break;
}

When a case expression satisfies the switch argument expression, that branch is followed.


#3

ok, I see that does work. But what’s not working for me is:
‘’’
let athleteFinalPosition = 1;

switch (athleteFinalPosition) {
case athleteFinalPosition < 2:
console.log(‘You get the gold medal!’);
break;
case 4-2:
console.log(‘You get the silver medal!’);
break;
case 5-2’:
console.log(‘You get the bronze medal!’);
break;
default:
console.log(‘No medal awarded.’);
break;
}
‘’’
Is there anyway to satisfy that first case expression in this manner? may be write it a different way?


#4

If you write a boolean expression, then it will yield true or false.

    x = 1
    switch (true) {
    case x < 2: action; break;
    case x > 2: action; break;
    default: action
    }

#5

I see. Thank you for the quick replies.