Can I use switch here?

Hello!

New to the forum so any constructive criticism is welcomed.

I’m working on learning JS and came up on a hiccup on one of the challenges “Basic JavaScript: Return Early Pattern for Functions”. In the challenge, you are asked to exit the function with undefined if either of the args (a, b) are less than zero. I was able to successfully complete the challenge using if but I initially attempted it via switch and was not successful. The following code is what I attempted and it does return NaN but not undefined. Is it possible to do this via switch?

function abTest(a, b) {
  switch (a, b) {
    case (a < 0):
    case (b < 0):
    return;
    break;
  }
  return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
console.log(abTest(2,2));

Nope.

cases do not work like ifs. You don’t put a logical expression in them.

1 Like