Return Early Pattern for Functions Exercise

Return Early Pattern for Functions Exercise
0

#1

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

#2

Hi,

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

Cheers,
Nitin


#3

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

You’re welcome!

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

Happy to help!


#5

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


#6

can someone explain to me why

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

doesn’t work but

if (a<0 || b<0)

does?!!!


#7

When you write;

if (a || b < 0) {

JavaScript sees this as two comparisons, but evaluates left to right. So, first a || b is evaluated as true, because when strings or numbers are compared in such a way, they get coerced into the Boolean value true. So then, then the next comparison is becomes true < 0. When this comparison is made, true gets coerced to 1 so you really have the expression 1 < 0, which is most definitely false. Some languages like Python let you make combined comparisons like you tried to right, but not JavaScript. You must group them separately as the in the 2nd if statement condition you show above.


#8

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.


#9

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).


#10

I did not consider the operator precedence. Good information! Thanks!


#11

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