Return Early Patter

I have already passed this test using if statements but when i try using the switch statement, all but 2 conditions are met. Is there a way it can be done?

  **Your code so far**

// Setup
function abTest(a, b) {
// Only change code below this line

if (a<0){
return undefined;
}
else if (b<0){
return undefined;
}

// Only change code above this line

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

abTest(2,2);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0

Challenge: Return Early Pattern for Functions

Link to the challenge:

Hi @mbonuvictor27 !

I guess you could opt to use a switch statement like this:

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

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

abTest(2, 2);

But I would personally just use one if statement instead of two

// Setup
function abTest(a, b) {
  // Only change code below this line
  if (a < 0 || b < 0) {
    return undefined
  }
  // Only change code above this line

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

abTest(2, 2);

Switch statements work well if you want to clean up a lengthy if/else statement.
But in this case, I think the better option is to go with just one if statement.

Hope that helps!

1 Like

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