Return Early Pattern for Functions help++

Tell us what’s happening:
I’m having a hard time understanding this one. Any insight?

Your code so far


// Setup
function abTest(a, b) {
  // Only change code below this line
  
  
  
  // 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 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

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

Hello @guttervacay.
The lesson about the return statement says that when a return statement is reached, the execution of the current function stops and control returns to the calling location. Whatever there is still in that function that has been put after the return statement will NEVER be executed.

let randomNameForAFunction = function(){
  let num = 0;
  return num;
  let increasedNum = num + 7;
  return increasedNum;
}

console.log(randomNameForAFunction());
//Will always output 0 because the flow of the function will stop at the first return encountered

In case of loops/switches/if-else, you need to follow the control dictated by those statements

let randomNameForAFunction = function(IAmABoolean){
  if(IAmABoolean){
    return 0;
  }
  return 7;
}

console.log(randomNameForAFunction(true));
//Will always output 0 because the flow of the function will stop at the first return encountered. The parameter is true, so the part inside the body of the `if` is executed

console.log(randomNameForAFunction(false));
//Will always output 7 because the first return encountered is actually the second that is written inside the function. The parameter is false, so the part inside the body of the `if` is skipped

Edit: knowing this, the lesson asks you to modify the function abTest so that if a or b are less than 0 the function will immediately exit with a value of undefined and it also warns you on the fact that undefined is not a string, but a JS keyword (it’s actually one of the primitive values).

Edit 2: it’s also a way to return early from some function when the conditions are not met. In the example on the challenge, the condition for a square root is that the number to which it is applied is greater or equal to zero. When that is not the case, exit early from the function and avoid the computation of Math.sqrt(a) + Math.sqrt(b) which would cause errors.