Return Early Pattern for Functions Exercise

This is the code I put in. It is telling me that it is not returning “undefined” for negative numbers, but when I manually run it the test screen says undefined. Is this a bug or is there something wrong with my code?

// Setup
function abTest(a, b) {
  // Only change code below this line
 if (a < 0 || b < 0) {
   return "undefined";
 }  
  else {
  // 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);
4 Likes

Hi,

Have you tried using undefined without the quotes? undefined is a keyword, not a String literal. :slight_smile:

Cheers,
Nitin

12 Likes

That was it. Thanks NitinNair89. Boy the little things can really get you. I think it is a good thing I’m making lots of little mistakes, because it will make me more aware later down the road when I’m doing coding for pay.

4 Likes

You’re welcome!

I did the same mistake. The console.log helped me realize what I did that time. :slight_smile:

Happy to help!

1 Like

https://forum.freecodecamp.com/t/return-early-pattern-for-functions-exercise/17496?u=anthony-bradley

No need for ‘else’ after the ‘if’ section. Serves no purpose.

can someone explain to me why

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

doesn’t work but

if (a<0 || b<0)

does?!!!

2 Likes

ah okay, I’ve been learning python and JavaScript side by side which might account for the mix up. I thought it would have worked for JS but not python. Thanks for clearing that up for me.

The less than operator has higher precedence than || operator, so the b < 0 bit is evaluated first. Then it becomes a || <some boolean value>. It will always evaluate to true as long as a is not zero (or any falsy value).

5 Likes

// 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));
}

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

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