Return Early Pattern for Functions help

Return Early Pattern for Functions help
0

#1

Tell us what’s happening:
Please help, I have use this code as well (i.e … if (a < 0 || b < 0) { return undefined; }) but again the system complained and gave error

Your code so far


// Setup
function abTest(a, b) {
  // Only change code below this line
  if (a < b){
    console.log(a * b + 2);
  }
  else if (a === b) {
    console.log(a * b * 2);
  }
  else if (a < 0 && b > 0 || 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);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions


#2

try checking or a < 0 and b < 0 without worrying about what the other values are at the beginning

for eg. if a is -1 and b is 0 your code will log (a * b + 2) because -1 is less than 0
you want it to return undefined right away because of the -1


#3

Thanks for your assistance but could you please explain why only one line of code (i.e if (a < 0 || b < 0) { return undefined }) solves all the challenge?
In other word what does this line (return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));) of code do?
regards


#4

well they only asked you to do one thing. Return undefined if a or b is less than 0.
That’s why you only need a single if statement to pass.

The other line is just showing you what will be done if a and b are both >=0
(they will be used in a math equation which is finding the square root of a and adding it to the square root of b, then raising that to the power 2, and rounding the result finally.)


#5

Thanks for explanation, it means that I should wait to know math and keep going until I get to math.


#6

Hey Hrr, you don’t need it, you can keep going,
What you need to know for this exercise is that an empty return defines the value for undifined,
so you just need to apply the condition they ask you before, if that condition is true that you can give the empty return.

here if you still are with some doubts here is a solution.

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

#7

Thank you so much dear Elthask, I’ve already done that
regards