Return Early Pattern for Functions. stuck

Tell us what’s happening:

Not able to figure out what method to use. case? or setting an if else?

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

The challenge asks you to stop the function if at least one of the numbers is negative returning undefined

You need three things:

  • execute the code that stops the function only on certain conditions (what statement can you use?)
  • check if the variables respect that condition
  • stop the function returning undefined

What of these have you trouble with?

all of them. I’m not really sure where to begin.

Hey ShazzyDigital how u r doin? So basically when use return statement inside function javascript engine that execute code inside function body execute all the codes till return when it sees return it stops there and give back or return whatever expression or code it sees in return from that function and it does not execute any code after return statement. This is what asked in challenge. Return early state of for function exit. So that’s why you did not see code with Math.methods().

Does an example of returning early help?

function isThisMyName(name) {
    if (name !== 'Sam') {
        return 'Nope';
    }
    return 'Yep';
}

console.log(isThisMyName('Bill')); // Nope
console.log(isThisMyName('Sam')); // Yep

yes! thank you so much

As a side note, you can also use ternary for stuff like this i.e. when a function is going to return something based on one condition, rather than having:

if (conditionIsTrue) {
    return true;
}
else {
    return false;
}

…you can just return the result of the condition itself:

return (conditionIsTrue);

… so we could do this from the previous example:

function isThisMyName(name) {
    return (name !== 'Sam') ? 'Nope' : 'Yep';
}

console.log(isThisMyName('Bill')); // Nope
console.log(isThisMyName('Sam')); // Yep

You don’t need the parenthesis around the condition (name !== 'Sam') but I find it easier to read like that. Food for thought :slight_smile: