Why doesn't my solution work? Return Early Pattern for Functions

I was stuck on the Basic JavaScript exercise: Return Early Pattern for Functions. The goal is to get the function to immediately return undefined and stop executing if variable a or b are less than 0. The function is abTest(a,b). There are also other requirements, like: abTest(2,2) should return a number && abTest(2,2) should return 8

My code would cause me to pass the portion that says abTest(-2,2) or (2,-2) should return undefined yet it would not pass the rest of the requirements.

Here is an example of what I was entering which would pass the 2 “undefined” requirements but would not pass the rest:

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

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

// Change values below to test your code
abTest(2,2);

All I changed to get all requirements to pass was entering the if statement as this instead:

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

My assumption is that with (a || b < 0) is that it’s reading it as “if a exists, or if b is less than 0…”

Your assumption is correct, the if statement does say “IF a OR (IF b < 0)”. You have to be explicit with Boolean logic

It isn’t quite saying “IF a exists” though, the condition has to be true or false, so what JS does is convert whatever “a” is to a true/false value. 0 is false, any other number is true, so if “a” exists but is 0, that would be treated as false - always try to make sure the condition is an actual true/false value, because it’s a very common source of bugs when that isn’t the case.

1 Like

Thank you for the confirmation! It was the only thing that made sense, I just wasn’t realizing that possibility when I kept trying to pass the exercise and didn’t want to assume that was the exact issue. Your explanation helped greatly!

1 Like