Return Early Pattern for Functions

Return Early Pattern for Functions
0

#1

this setup

// 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);
See i got see below wrong
abTest(-2,2) should return undefined
abTest(2,-2) should return undefined


#2

we want to know more about the problem.

who are the requirements?

a minur observation is that sqrt function cannot contain negative values


#3

the answer is

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

if(a<0 || b<0){
return;
}

// 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);


#4

What @amazigh1989 said.

But just to add: Since apparently the test specifically asks for ‘undefined’ to be returned in those cases, it would be good practice to actually return that ‘undefined’ explicitly, i.e.:

if(a<0 || b<0){
  return undefined;
}

This helps readability of your code. People will know that you really do intend to return undefined.


#5

Hi,

Isn’t if(a<0 || b<0){
equivalent to "if ((a || b ) <0 ) {
???


#6

No. Look at the following example:

var a = 10;
var b = -1;

console.log(a < 0 || b < 0); 
// above displays true because a<0 is false and b<0 is true, so true || false is true

console.log((a || b) < 0) 
// displays false because (a || b) is 10  and  10 < 0 is false

#7

:ok_hand:t2:
its makes sense this way


#8