I'm stuck here please....Return Early Pattern for Functions

Tell us what’s happening:
I still can’t get it right or maybe I don’t understand the lesson…

Your code so far


// Setup
function abTest(a, b) {
  // Only change code below this line
 if (a || b < 0 ){
    return undefined;
  }
    

  // 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/74.0.3729.169 Safari/537.36.

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

This isn’t doing what you think it does. This is a very common mistake for beginners. Heck, one of the junior devs at work made this exact mistake at work today, not joking. You think it is checking if either a or b is less than zero.

If I remember correctly, comparison operators have a higher precedence than the logical or, so really you are seeing if b is less than zero, which evaluates to a boolean, You are then or-ing that with a. If a is truthy, the whole thing will evaluate to a and if not, the whole thing will evaluate to whatever result of b < 0 was.

Some of that may sounded weird - I don’t know if you’ve gotten into the weirdness of how JS handles logical or’s and logical and’s. Don’t worry about it if you aren’t there yet.

The important thing is that in English we can say “if a or b is less than zero” and we know what it means. But for a computer (at least in JS) we need to spell it out differently as “if a is greater than zero or (if) b is greater than zero”. You need to do each of those comparisons separately. They can be on the same line and all, but they have to be spelled out.

Like I said, many people make this mistake in the beginning. In makes sense to a human brain, but it’s not how computers think.

2 Likes

That was great…
Thanks for briefing me about the comparison operators and logical or…could be misunderstood sometimes…
And thanks for sharing the incident at work too…lol
I got it now…

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

// Change values below to test your code
abTest(2,2);
1 Like