Basic JavaScript - Return Early Pattern for Functions

Tell us what’s happening:
This function works below … but why not this logic works
if((a||b)< 0){
return undefined;
}

Your code so far

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

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

  // Only change code above this line

  return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}

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/97.0.4692.71 Safari/537.36

Challenge: Basic JavaScript - Return Early Pattern for Functions

Link to the challenge:

You would do the parentheses first here, so you would get either true or false for (a || b) and then you would check if that answer is less than 0. If you test this you will see that either true < 0 or false < 0 always returns false. So (a || b) < 0 always returns false.

1 Like

Actually it looks like a || b would return “a” if a is thruthy value, else return the value of “b”, which again would not satisfy the condition we want to meet. For example 2 || -3 would return 2, which will then be checked for 2 < 0 === false.

1 Like

Yeah, it’s a common misunderstanding that || and && “return” a boolean value. They are actually work as selectors - they are not technically a boolean AND or OR. We often use them as such, but technically return a truthy or falsy, as one of the values.

You can read more here.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.