Switch statements and strict comparison

Hi, there’s a thing about switch statements I don’t clearly understand. The curriculum says cases get tested with strict comparison, but in the practice a single equal sign is used. Why is this so? Thank you very much. I’m re-doing the whole JavaScript curriculum and I want to understand everything.

I don’t know what you mean by, "…but in the practice a single equal sign is used. " That would be an assignment operator, not comparison.

They mean that when it compares the values, it is a strict comparison (like ===) that does not coerce the type.

For example,

const value = 1;
switch (value) {
// ...

that would match for:

case 1:

but not for

case '1':

It has nothing to do with the assignment operator on the first line.

1 Like

Ah, that’s clear.
This confused me:

function caseInSwitch(val) {
  var answer = "";
  // Only change code below this line
  switch (val) {
    case 1:
      answer = "alpha";
      break;
    case 2:
      answer = "beta";
      break;
    case 3:
      answer = "gamma";
      break;
    case 4:
      answer = "delta";
      break;
  }
  // Only change code above this line
  return answer;
}
// Change this value to test
caseInSwitch(1);

Hi there,

The switch statement does a strict comparison between the parameter and the case.

Say I have a switch statement for cleaning the house:

function robotMaid(chore) {
     job = ""
     switch(val) {
     case dishes:
     job = "Do the dishes";
     break;
     case laundry:
    job= "Do the laundry";
    break;
     }
}

The robotMaid function is going to take the chore and see if it matches the case using strict equality (===). The = is just to assign what job it’s supposed to do in each case.

I hope my silly example makes sense.

2 Likes

@cherylm Your example is not silly. It was a nice way of explaining it. With your example and @kevinSmith’s explanation the thing got clear for me. Thank you both.

1 Like