Can I use an alternative solution to Basic JavaScript: Return Early Pattern for Functions

Tell us what’s happening:
I can solve the problem with the if statement but I was wondering why it doesn’t work with the switch.

Your code so far


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

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

abTest(2,2);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 OPR/73.0.3856.329.

Challenge: Return Early Pattern for Functions

Link to the challenge:

hello. I did some browsing and if you replace the statement in your switch with true, like switch(true): it will run the code as intended
Also, you dont have to put break; after a return statement, as it breaks the loop by default

1 Like

a switch has this sintax:

switch (commonExpression) {
  case expr1:
  ...
  break;
  case expr2:
  ...
 break;
}

and converted to an if statement it is like this:

if (commonExpression === expr1) {
   ...
} else if (commonExpression === expr2) {
  ...
}

you can put whatever instead of “commonExpression” and “expr1” and “expr2”, you just need to know that they are compared like that

in your case the comparison is (a,b) === (a<0) or (a,b) === (b<0) so it is always false

2 Likes

Is general, I’m not a big fan of using a switch like that. A switch is for comparing one valuable to many possibilities. An if-else is for more complex comparisons.

Side note: it’s really best to use indentation for readability and maintainability. It’s good to get in the habit now while you are on the less complex lessons so that others can read your code in future lessons of you have any questions.

1 Like

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