Return Early Pattern for Functions- need help to understand the question

Tell us what’s happening:

Can someone help me understand this question?

Your code so far


// Setup
function abTest(a, b) {
  // Only change code below this line
  return a < 0 && b < 0;
    
  
  
  
  // 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/73.0.3683.86 Safari/537.36.

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

I guess the task need us to return and get out of the function if the value is not we wanted, so that the whole logic will not be run if the value is not a valid value so to reduce the chance of error.

Can you expand on what you don’t understand?

Thanks for the reply garyc.
So to come out of the function, we should use return statement. But i do not understand how to get undefined value.

Hi ArielLeslie. I don’t understand how to return undefined value.

undefined is the default return value in JavaScript, so there are three ways to return it:

function explicitUndefined() {
  return undefined;
}

function implicitUndefined() {
  return;
}

function noReturnStatement() { }

All three of these functions return undefined.

Combining this with conditional logic:

function isItEven(num) {
  if (num % 2) {
    return;
  }

  return 'Yes, it is!';
}

isItEven(43); // returns `undefined`
1 Like

Thanks lionel-rowe. The explanation was really helpful. I tried following it but it still throws some error when i am checking it for a = 3 and b = 8. it is behaving fine for a = 2 and b = 2.

if (a == 2 &amp;&amp; b == 2){

return 8;

}elseif (a == 2 &amp;&amp; b == 8){

return 18;

}elseif( a == 3 &amp;&amp; b == 3){

return 12;

}else {

return;

}

You need to check if at least one of the numbers is negative and return undefined if that is the case

You are doing something completely different
There is already the code that calculate the result, you don’t need to do that
You are hardcoding the numbers, don’t hardcore numbers, just use the variables so that your function can still be used outside the tests

Also, it is not elseif, but else if

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums