Return Early Pattern for Functions I can't think of the code to use for this

Tell us what’s happening:

Having trouble getting the undefined one.

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.

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

Early Return is a common and widely used pattern.
Imagine it like a way to write an if else but for cases where you want to stop your function before doing anything.

Imagine we have a greetUser function where we say hello to our logged user, that receive either the user name or false if the user if not logged.
Of course we don’t want to say hello to a “false” user.

We can write it like this

/**
 * @params {(string \| boolean)} username - our user. false if not logged
 */
function greetUser(username) {
  if(username) {
    // say hello to the user
    return ('Welcome back '+ username)
  } else {
    // do nothing
   return false;
  }
}

greetUser('CodeSmity') // 'Welcome back CodeSmity'
greetUser(false) // false

We can rework it to return false before doing whatawer it has to do in case the user is logged like so

/**
 * @params {(string \| boolean)} username - our user. false if not logged
 */
function greetUser(username) {
  // user is not logged. Return false
  if (!username) return false;

  return 'Welcome back ' + username
}

greetUser('CodeSmity') // 'Welcome back CodeSmity'
greetUser(false) // false

The advantage is that we can write the rest of the function body knowing that we have the right input, since we did our checks in advance.

Hope this helps :+1:

1 Like

Thank you Marmiz for the hint, very helpful.

// Setup
function abTest(a, b) {
// Only change code below this line

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

1 Like