Why cant we use switch instead of if/else in return early pattern for function

here,
function abTest (a, b) {
// Only change code below this line
switch (a, b) {
case (a<0 || b<0):
return undefined;
break;
}

// Only change code above this line

return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}

abTest(2,2);

That’s not proper switch syntax.

You can read more about switch here:

Or review the FCC lesson here:

2 Likes

To expand, you could go between if/else and switch with something like this:

if (pet === "dog") {
  throwBone();
} else if (pet === "cat") {
  ignore();
} else if (pet === "fish") {
  cleanBowl();
}
// functionally equivalent switch
switch(pet) {
  case "dog":
    throwBone();
    break;
  case "cat":
    ignore();
    break;
  case "fish":
    cleanBowl();
    break;
}

Where your conditions are checking if a single expression (in this case pet) is strictly equal (===) to some set of values.

2 Likes

And just to be clear, you 100% can use switch for a “return early pattern”. I do it all the time. But @colinthornton is right that you have some syntax/conceptual problems with switch. If you look at his last example, if you replaced those break statements with returns, you’d have a return early pattern.

And just to be clear, with this:

switch (a, b) {
  case (a<0 || b<0):
    return undefined;
    break;
}

there is a “sneaky” way to accomplish this:

switch (true) {
  case (a<0 || b<0):
    return;
  // other cases, presumably
}

You can create a list of cases with logic in them and it will hit on the first one that is true. Some people don’t like this pattern. It’s a bit of a Yoda notation, inverting the logic. But there is nothing explicitly wrong with it. I try to avoid it just because it is a little odd and it might slow readability.

Also notice that I removed the break - once you return there is no need for it. And also, if you don’t return anything, that is the same as returning undefined. You never need to explicitly return undefined. (Unless you are trying to be explicit or if the linter complains.)

But you should master what Colin is talking about first - that is the standard way to use it.

1 Like

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