// 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.
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.