Simple question on Switch Statements

So, I’m learning if statements and they seem pretty straight forward so far. However, I’m a little bit confused on how “=” and “===” works with these?

so, normally “=” assigns
and “===” is a strict comparison

however, when I try to use “===” in the example below it will always return default no matter what the value of “roll” is. This confused me and I decided to simply put “=” and the code worked as intended.

can someone explain what is going on here? Shouldn’t this be working with “===”?

let roll = 5;

switch(roll) {
    case roll = 1:
        console.log('you rolled a 1');
        break;
    case roll = 2: 
        console.log('you rolled a 2');
        break;
    case roll = 3:
        console.log('you rolled a 3');
        break;
    case roll = 4: 
        console.log('you rolled a 4');
        break;
    case roll = 5:
        console.log('you rolled a 5');
        break;
    case roll = 6: 
        console.log('you rolled a 6');
        break;
    default:
        console.log('your turn is skipped! Sorry!')
}

Don’t do this!

Don’t use === either!

The case is the literal value you want to match against, so 1 in this example.

interesting, I was thrown off because of the example below, but I think I understand it now.

const today = 'monday' 


switch (true) {
    case today === 'monday':
        console.log(`today is ${today}`);
        break;
    case today === 'tuesday':
        console.log(`today is ${today}`);
        break;
    case today === 'wednesday':
        console.log(`today is ${today}`);
        break;
}

That’s a bad example. Don’t do that.

const today = 'monday' 

switch (today) {
  case 'monday':
    console.log(`today is ${today}`);
    break;
  case 'tuesday':
    console.log(`today is ${today}`);
    break;
  case 'wednesday':
    console.log(`today is ${today}`);
    break;
}

what would be the proper way of writing this then?

Like this

1 Like

Sorry I didn’t notice you had already posted it. I appreciate the help! :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.