Return Early Pattern for Functions (abTest(2,-2); ?)

Can someone explain why abTest is (2,-2);??

// Setup
function abTest(a, b) {
  // Only change code below this line
  if (a < 0 || b < 0) {
   return "undefined";
  else {
  // 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

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


I don’t understand

Can someone explain why abTest is (2,-2);??

It isn’t. That is an example function call to test the code.

Anyway, there are basically two problems with your code. First:

return "undefined";

You are not supposed to return a string that says “undefined” but are supposed to return the JavaScript type, undefined - remove the quotes.

Secondly, you are missing a closing brace. That is because you have added in an else { that is not needed. It is not needed because it the first if is true, then it will return and it will never see any code. That is the point of the exercise, the “return early” or “fail fast” pattern. You bail out of the function with a return statement so you will never hit that other code anyway so the else is redundant. The else would work if you added a } after the return, but is completely unnecessary.

1 Like

@kevinSmith Im sorry I had the starting code and the finished code in two separate browsers trying to figure out why that worked and I pasted the wrong one! But I still dont understand how to actually figure out the function call? Like what does it mean? Thank you


I’m still not sure what you are asking. Are you asking what functions do? How they work? If that is the case, then you have some research to do before continuing.

Maybe you are asking about why this is here in the code:

// Change values below to test your code

That is completely optional code. It isn’t required for anything to work. You can change the values to test the code, by seeing console.log statements in the gray box below. But you don’t need it. It’s just calling the function with some test values. You can change the values to see what happens or delete it entirely and still pass the test.

Im sorry yes I was asking why its in that code - I just didnt see how/if it tied in to making the code work and youve just answered that it doesnt so I understand now, thanks again.